Summarize sorted invoice numbers as ranges
Your task
A billing report lists the invoice numbers a batch job processed. Long runs of numbers are easier to read as ranges.
Write summarize_ranges(nums) that returns the numbers written as a list of runs.
Input and output:
nums: a list of up to 10,000 distinct integers in ascending order, each between -1,000,000,000 and 1,000,000,000.- Returns a list of strings, one per run, in the same order as the numbers.
Rules:
- A run is a longest stretch of consecutive integers, each exactly 1 more than the one before it.
- A run of two or more numbers is written as its first number, then
->, then its last number, with no spaces. - A run of one number is written as just that number.
- Numbers are written in plain decimal, with a leading
-for negatives. - An empty list returns an empty list.
Examples
summarize_ranges(nums: list[int]) -> list[str]Example 1
Input
summarize_ranges([0, 1, 2, 4, 5, 7])Output
["0->2", "4->5", "7"]Example 2
Input
summarize_ranges([-5, -4, 0, 2, 3])Output
["-5->-4", "0", "2->3"]