#360 · Parsing · Advanced · 125 XP · about 25 min
Timers and calendar apps accept durations typed by people, such as "1h 30m", "2d4h", "90s" or "1 hour, 20 minutes and 5 seconds". Write parse_duration(text) that returns the length of the duration in seconds, or -1 if text is not a valid duration.
A duration is one or more parts. Each part is a whole number (digits only) followed by a unit, with or without spaces between them. These are the units, and upper and lower case letters are both fine:
d, day, days (86,400 seconds)h, hr, hrs, hour, hours (3,600 seconds)m, min, mins, minute, minutes (60 seconds)s, sec, secs, second, seconds (1 second)The rest of the rules:
and, or a comma and then and. Spaces may go anywhere around a comma. The word and needs a space after it, and a space before it unless it comes right after the comma.and that is not between two parts.parse_duration('1h 30m') # returns 5400 parse_duration('2d4h') # returns 187200 parse_duration('90s') # returns 90 parse_duration('1 hour, 20 minutes and 5 seconds') # returns 4805 parse_duration('30m 1h') # returns -1
The last one is invalid because minutes come before hours.
text has at most 200,000 characters, all ASCII, and its only whitespace is spaces.First solves only, ranked by stars and then time.