You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
concepts: regular expression, unit conversion, error handling
703
+
704
+
[Instruction]
705
+
Create a Python function that converts a string representation of a time duration into its total number of seconds.
706
+
The input string should follow a format that includes a numeric part followed by a time unit suffix without any spaces between.
707
+
The time unit can be seconds in the form of 's' or 'sec', minutes in the form of 'm' or 'min', hours in the form of 'h' or 'hour', and days in the form of 'd' or 'day' (units are in small case).
708
+
If the input format is invalid, the function should raise a ValueError.
709
+
710
+
```python
711
+
assert parse_duration('15s') == 15
712
+
assert parse_duration('2min') == 120
713
+
assert parse_duration('1h') == 3600
714
+
assert parse_duration('1d') == 86400
715
+
try:
716
+
parse_duration('30')
717
+
except ValueError as e:
718
+
pass
719
+
```
720
+
721
+
[Response]
722
+
[Reasoning]
723
+
The desired function aims to transform a string representation into its total number of seconds. The implementation can be split into two parts:
724
+
725
+
Input validation:
726
+
1. The input string includes two parts: a number as the prefix and the unit as the suffix.
727
+
2. We can use regular expression to assert the prefix must be a number (d+) and suffix must be one of s/sec/m/min/h/hour/d/day.
728
+
3. If the input string cannot the regular expression, we raise a ValueError.
729
+
730
+
Result computation:
731
+
1. Based on the matches of regular expression, we capture the number and unit part.
732
+
1. We convert the unit to seconds: 's'/'sec' -> 1 second, 'm'/'min' -> 60 seconds, 'h'/'hour' -> 3600 seconds, 'd'/'day' -> 86400 seconds.
733
+
2. We multiply the seconds of the unit and the prefix number and return it as an integer.
734
+
735
+
[Implementation]
736
+
Here's how you can implement this:
737
+
738
+
```python
739
+
import re
740
+
741
+
def parse_duration(duration_str):
742
+
# Define a regex pattern to match the input string
0 commit comments