Skip to content

Update summarize_ranges.py #912

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 13 additions & 15 deletions algorithms/arrays/summarize_ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,20 @@
"""


def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
from typing import List

def summarize_ranges(array: List[int]) -> List[str]:
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array[i] != num:
res.append((num, array[i]))
it = iter(array)
start = end = next(it)
for num in it:
if num - end == 1:
end = num
else:
res.append((num, num))
i += 1
return res
res.append((start, end) if start != end else (start,))
start = end = num
res.append((start, end) if start != end else (start,))
return [f"{r[0]}-{r[1]}" if len(r) > 1 else str(r[0]) for r in res]