easy +8 pts

Parse range notation

Expand compact range strings like '1-3,5,7-9' into a sorted list of integers.

Write a function `parse_ranges(ranges: str) -> list[int]` that takes a string like `"1-3,5,7-9"` and returns a sorted list of all integers covered by the ranges. **Rules:** - The input string consists of comma-separated tokens. Each token is either: - A single non-negative integer (e.g., `"5"`), or - A range in the form `"a-b"` where `a` and `b` are non-negative integers and `a <= b` (e.g., `"1-3"`). - Tokens may have leading/trailing spaces, but no other whitespace. Commas may be surrounded by spaces. - Duplicates may occur (e.g., `"1-2,2-3"`); they must be removed in the output. - The output must be sorted in ascending order. Return the sorted list of integers (with no duplicates).

Constraints

- `0 <= a <= b <= 10^6` for each range. - The number of tokens is at most 1000. - The total number of integers before deduplication is at most 10^5. - Do not use any third-party libraries; only the Python standard library.

Example

['>>> parse_ranges("1-3,5,7-9")', '[1, 2, 3, 5, 7, 8, 9]', '>>> parse_ranges("1-2,2-3")', '[1, 2, 3]', '>>> parse_ranges("1")', '[1]']
8 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Split the input string by commas, then strip each token of whitespace.
For each token, check if it contains a hyphen. If yes, split on the hyphen and expand the inclusive range.
Collect all numbers in a set to automatically remove duplicates, then return sorted(my_set).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.