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 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
+ """
12
23
13
- def generate_sum_of_subsets_soln (nums : list [int ], max_sum : int ) -> list [list [int ]]:
14
24
result : list [list [int ]] = []
15
25
path : list [int ] = []
16
26
num_index = 0
@@ -34,7 +44,21 @@ def create_state_space_tree(
34
44
This algorithm follows depth-fist-search and backtracks when the node is not
35
45
branchable.
36
46
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]]
37
60
"""
61
+
38
62
if sum (path ) > max_sum or (remaining_nums_sum + sum (path )) < max_sum :
39
63
return
40
64
if sum (path ) == max_sum :
@@ -51,16 +75,7 @@ def create_state_space_tree(
51
75
)
52
76
53
77
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
61
80
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