Skip to content

Commit bb413d1

Browse files
authored
Merge pull request #1276 from ivan1016017/may20
adding summary ranges algo
2 parents cf41627 + a257a95 commit bb413d1

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def summaryRanges(self, nums: List[int]) -> List[str]:
6+
7+
len_nums = len(nums)
8+
9+
if len_nums == 0:
10+
return []
11+
elif len_nums == 1:
12+
return [f'{nums[0]}']
13+
else:
14+
answer = list()
15+
16+
pre = start = nums[0]
17+
18+
for i in nums[1:]:
19+
if i - pre > 1:
20+
answer.append(f'{start}->{pre}' if pre-start > 0 else
21+
f'{start}')
22+
start = i
23+
pre = i
24+
25+
answer.append(f'{start}->{pre}' if pre-start > 0 else f'{start}')
26+
27+
return answer
28+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_16\
3+
.summary_ranges import Solution
4+
5+
class SummaryRangesTestCase(unittest.TestCase):
6+
7+
def test_empty(self):
8+
solution = Solution()
9+
output = solution.summaryRanges(nums=[])
10+
target = []
11+
self.assertEqual(target, output)
12+
13+
def test_single_element(self):
14+
solution = Solution()
15+
output = solution.summaryRanges(nums=[1])
16+
target = ['1']
17+
self.assertEqual(target, output)
18+
19+
def test_several_elements(self):
20+
solution = Solution()
21+
output = solution.summaryRanges(nums=[0,1,2,4,5,7])
22+
target = ["0->2","4->5","7"]
23+
for k, v in enumerate(target):
24+
self.assertEqual(v, output[k])

0 commit comments

Comments
 (0)