Skip to content

Commit deb0a7d

Browse files
committed
Refactor to simplify and make more readable
1 parent ac979fb commit deb0a7d

File tree

2 files changed

+10
-13
lines changed

2 files changed

+10
-13
lines changed

list_things/src/continuous_subset.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,18 @@
44

55
def continuous_subset_adding_up_to(full_set: list[int], target_sum: int) -> Optional[list[int]]:
66
accumulated_sums = list(accumulate(full_set))
7-
87
slice_length = 1
98
list_length = len(full_set)
9+
1010
while slice_length <= list_length:
1111
left_index = 0
12+
right_index = slice_length - 1
1213
while left_index <= list_length - slice_length:
13-
right_index = left_index + slice_length - 1
14-
if left_index == 0:
15-
if accumulated_sums[right_index] == target_sum:
16-
return full_set[left_index:slice_length]
17-
elif accumulated_sums[right_index] - accumulated_sums[left_index - 1] == target_sum:
18-
if slice_length == 1:
19-
return [full_set[right_index]]
20-
else:
21-
return full_set[left_index : left_index + slice_length]
14+
to_subtract = 0 if left_index == 0 else accumulated_sums[left_index - 1]
15+
if accumulated_sums[right_index] - to_subtract == target_sum:
16+
return full_set[left_index : left_index + slice_length]
2217
left_index += 1
18+
right_index += 1
2319
slice_length += 1
2420

2521
# Not able to find a subset adding up to target

list_things/tests/test_continuous_subset.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ def test_sublist_with_unnattainable_target_returns_none(self):
1313
([1], 1, [1]),
1414
([1, 2, 3, 4], 1, [1]),
1515
([1, 2, 3, 4], 3, [3]),
16+
([1, 2, 4, 5], 3, [1, 2]),
1617
([1, 2, 3, 4], 6, [1, 2, 3]),
1718
([1, 2, 3, 4], 10, [1, 2, 3, 4]),
1819
([1, 2, 3, 4], 9, [2, 3, 4]),
@@ -31,9 +32,9 @@ def test_returns_subset_adding_up_to_target_sum(self, full_set, target_sum, expe
3132
(1000, 13076),
3233
(10000, 130476),
3334
(100000, 1500090),
34-
(1000000, 1500090), # Takes about 350ms
35-
(10000000, 1500090), # Takes about 642ms
36-
(10000000, 97000900), # Takes about 30s
35+
(1000000, 1500090), # Takes about 325ms
36+
(10000000, 1500090), # Takes about 600ms
37+
# (10000000, 97000900), # Takes about 30s
3738
],
3839
)
3940
def test_works_with_larger_lists(self, list_size, target_sum):

0 commit comments

Comments
 (0)