Skip to content

Commit 40c944c

Browse files
authored
Update summarize_ranges.py (#912)
1 parent 1117ffe commit 40c944c

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

algorithms/arrays/summarize_ranges.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -6,22 +6,20 @@
66
"""
77

88

9-
def summarize_ranges(array):
10-
"""
11-
:type array: List[int]
12-
:rtype: List[]
13-
"""
9+
from typing import List
10+
11+
def summarize_ranges(array: List[int]) -> List[str]:
1412
res = []
1513
if len(array) == 1:
1614
return [str(array[0])]
17-
i = 0
18-
while i < len(array):
19-
num = array[i]
20-
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
21-
i += 1
22-
if array[i] != num:
23-
res.append((num, array[i]))
15+
it = iter(array)
16+
start = end = next(it)
17+
for num in it:
18+
if num - end == 1:
19+
end = num
2420
else:
25-
res.append((num, num))
26-
i += 1
27-
return res
21+
res.append((start, end) if start != end else (start,))
22+
start = end = num
23+
res.append((start, end) if start != end else (start,))
24+
return [f"{r[0]}-{r[1]}" if len(r) > 1 else str(r[0]) for r in res]
25+

0 commit comments

Comments
 (0)