From cad1020fdf1ce5b784866185c45762c2ed802cd5 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 15 Apr 2025 04:23:54 -0600 Subject: [PATCH] adding summary ranges --- .../summary_ranges.py | 27 +++++++++++++++++++ .../test_summary_ranges_round_15.py | 25 +++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_15/summary_ranges.py create mode 100644 tests/test_150_questions_round_15/test_summary_ranges_round_15.py diff --git a/src/my_project/interviews/top_150_questions_round_15/summary_ranges.py b/src/my_project/interviews/top_150_questions_round_15/summary_ranges.py new file mode 100644 index 00000000..08d24dbc --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_15/summary_ranges.py @@ -0,0 +1,27 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def summaryRanges(self, nums: List[int]) -> List[str]: + + len_nums = len(nums) + + if len_nums == 0: + return [] + elif len_nums == 1: + return [f'{nums[0]}'] + else: + answer = list() + pre = start = nums[0] + + for i in nums[1:]: + if i - pre > 1: + answer.append(f'{start}->{pre}' if pre-start > 0 else + f'{start}') + start = i + pre = i + + answer.append(f'{start}->{pre}' if pre-start > 0 else f'{start}') + + return answer + diff --git a/tests/test_150_questions_round_15/test_summary_ranges_round_15.py b/tests/test_150_questions_round_15/test_summary_ranges_round_15.py new file mode 100644 index 00000000..398bbb42 --- /dev/null +++ b/tests/test_150_questions_round_15/test_summary_ranges_round_15.py @@ -0,0 +1,25 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_15\ +.summary_ranges import Solution + +class SummaryRangesTestCase(unittest.TestCase): + + def test_empty(self): + solution = Solution() + output = solution.summaryRanges(nums=[]) + target = [] + self.assertEqual(target, output) + + def test_single_element(self): + solution = Solution() + output = solution.summaryRanges(nums=[1]) + target = ['1'] + self.assertEqual(target, output) + + def test_several_elements(self): + solution = Solution() + output = solution.summaryRanges(nums=[0,1,2,4,5,7]) + target = ["0->2","4->5","7"] + for k, v in enumerate(target): + self.assertEqual(v, output[k]) +