Python · Exercise 6 of 6 Previous
Intermediate
Red, green: build a duration parser from a test table
Write parse_duration(text) that turns strings like "90s", "2m", "1h30m" into a number of seconds. Units are h (3600), m (60) and s (1). A string may have several parts, in any order, and the parts are added together. A string that contains a space is invalid.
Invalid text must raise ValueError: an empty string, text with no unit like "45", text with an unknown unit like "5x", or extra characters like "1h 30m".
This is TDD: the table of cases is already written and the program prints a result for each one. Make every line say ok.
What Check tests
parse_duration("90s")is 90 and"2m"is 120parse_duration("1h30m")is 5400- Parts can come in any order and repeat units add up
- Invalid text raises ValueError
- The program prints no FAIL line
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.