easy +10 pts

Duration Human Readable

Convert a duration in seconds into a compact human-readable English string.

Write a function `format_duration(seconds: int) -> str` that converts a non-negative number of seconds into a human-readable English duration string. Rules: - The output uses the largest units possible: years (365 days), days (24 hours), hours (60 minutes), minutes (60 seconds), seconds. - Separate components with a comma and a space (', '), and use 'and' between the last two components if there are at least two. - Each unit is singular when the count is 1, otherwise plural (e.g., '1 second', '2 seconds'). - If `seconds == 0`, return `'now'`. - Do not include zero-value units unless the total is zero (in which case return 'now'). Examples: - `format_duration(62)` → `'1 minute and 2 seconds'` - `format_duration(3662)` → `'1 hour, 1 minute and 2 seconds'` - `format_duration(31536000)` → `'1 year'`

Constraints

- `0 <= seconds <= 2_147_483_647` (fits in 32-bit signed integer) - Complexity: O(1) time and space.

Example

>>> format_duration(1)
'1 second'
>>> format_duration(62)
'1 minute and 2 seconds'
>>> format_duration(120)
'2 minutes'
>>> format_duration(3600)
'1 hour'
>>> format_duration(3662)
'1 hour, 1 minute and 2 seconds'
>>> format_duration(0)
'now'
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Break the total seconds into years, days, hours, minutes, and seconds using integer division and modulo.
Build a list of non-zero component strings like '2 hours' and '1 minute'.
Join the list: all but the last with ', ', then append the last with ' and ' if more than one component.
Remember that 0 seconds should return 'now'.
Pluralize: add 's' if the count is not 1.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.