Skip to content

Commit

Permalink
Update summarize_ranges.py (keon#912)
Browse files Browse the repository at this point in the history
  • Loading branch information
zlhanq authored Feb 5, 2024
1 parent 1117ffe commit 40c944c
Showing 1 changed file with 13 additions and 15 deletions.
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]

0 comments on commit 40c944c

Please sign in to comment.