1
1
"""
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
3
3
value M, determine all possible subsets of the given set whose summation sum
4
4
equal to given M.
5
5
6
6
Summation of the chosen numbers must be equal to given number M and one number
7
7
can be used only once.
8
8
"""
9
9
10
- from __future__ import annotations
11
10
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 the subsets with sum
14
+ equal to 'max_sum'
15
+ >>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 9)
16
+ [[3, 4, 2], [4, 5]]
17
+ >>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 3)
18
+ [[3]]
19
+ >>> generate_sum_of_subsets_solutions([3, 34, 4, 12, 5, 2], 1)
20
+ []
21
+ """
12
22
13
- def generate_sum_of_subsets_soln (nums : list [int ], max_sum : int ) -> list [list [int ]]:
14
23
result : list [list [int ]] = []
15
24
path : list [int ] = []
16
25
num_index = 0
@@ -34,7 +43,9 @@ def create_state_space_tree(
34
43
This algorithm follows depth-fist-search and backtracks when the node is not
35
44
branchable.
36
45
46
+ >>> create_state_space_tree([1], 1, 0, [], [], 1)
37
47
"""
48
+
38
49
if sum (path ) > max_sum or (remaining_nums_sum + sum (path )) < max_sum :
39
50
return
40
51
if sum (path ) == max_sum :
@@ -51,16 +62,7 @@ def create_state_space_tree(
51
62
)
52
63
53
64
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())
65
+ if __name__ == "__main__" :
66
+ import doctest
61
67
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 )
68
+ doctest .testmod ()
0 commit comments