Skip to content

Commit e1115b5

Browse files
mindauglMaximSmolskiypre-commit-ci[bot]
authored
Add tests and cleanup sum_of_subsets algorithm (#12746)
* Add tests and cleanup sum_of_subsets algorithm. * Update sum_of_subsets.py * Update sum_of_subsets.py * Update sum_of_subsets.py * Update sum_of_subsets.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Maxim Smolskiy <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent c81cc26 commit e1115b5

File tree

1 file changed

+30
-15
lines changed

1 file changed

+30
-15
lines changed

backtracking/sum_of_subsets.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,26 @@
11
"""
2-
The sum-of-subsetsproblem states that a set of non-negative integers, and a
2+
The sum-of-subsets problem states that a set of non-negative integers, and a
33
value M, determine all possible subsets of the given set whose summation sum
44
equal to given M.
55
66
Summation of the chosen numbers must be equal to given number M and one number
77
can be used only once.
88
"""
99

10-
from __future__ import annotations
1110

11+
def generate_sum_of_subsets_solutions(nums: list[int], max_sum: int) -> list[list[int]]:
12+
"""
13+
The main function. For list of numbers 'nums' find the subsets with sum
14+
equal to 'max_sum'
15+
16+
>>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=9)
17+
[[3, 4, 2], [4, 5]]
18+
>>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=3)
19+
[[3]]
20+
>>> generate_sum_of_subsets_solutions(nums=[3, 34, 4, 12, 5, 2], max_sum=1)
21+
[]
22+
"""
1223

13-
def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:
1424
result: list[list[int]] = []
1525
path: list[int] = []
1626
num_index = 0
@@ -34,7 +44,21 @@ def create_state_space_tree(
3444
This algorithm follows depth-fist-search and backtracks when the node is not
3545
branchable.
3646
47+
>>> path = []
48+
>>> result = []
49+
>>> create_state_space_tree(
50+
... nums=[1],
51+
... max_sum=1,
52+
... num_index=0,
53+
... path=path,
54+
... result=result,
55+
... remaining_nums_sum=1)
56+
>>> path
57+
[]
58+
>>> result
59+
[[1]]
3760
"""
61+
3862
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
3963
return
4064
if sum(path) == max_sum:
@@ -51,16 +75,7 @@ def create_state_space_tree(
5175
)
5276

5377

54-
"""
55-
remove the comment to take an input from the user
56-
57-
print("Enter the elements")
58-
nums = list(map(int, input().split()))
59-
print("Enter max_sum sum")
60-
max_sum = int(input())
78+
if __name__ == "__main__":
79+
import doctest
6180

62-
"""
63-
nums = [3, 34, 4, 12, 5, 2]
64-
max_sum = 9
65-
result = generate_sum_of_subsets_soln(nums, max_sum)
66-
print(*result)
81+
doctest.testmod()

0 commit comments

Comments
 (0)