-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsum_sublists.py
39 lines (28 loc) · 904 Bytes
/
sum_sublists.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def is_solution(xs, s):
return sum(xs) == s
def is_viable(xs, s):
return sum(xs) <= s
def sumSubsets(xs, s):
subsets = [[]]
result = []
while subsets:
current = subsets.pop()
current_sum = sum(current)
if current_sum == s:
sorted_current = sorted(current)
if not sorted_current in result:
result.append(sorted_current)
continue
excluded_xs = xs[:]
for x in current:
excluded_xs.remove(x)
for x in excluded_xs:
if x > s:
break
new_state = current + [x]
if sum(new_state) <= s:
subsets.append(new_state)
return sorted(result)
print(sumSubsets([1, 2, 3, 4, 5], 5))
import cProfile
cProfile.run('print(sumSubsets([1, 1, 2, 4, 4, 4, 7, 9, 9, 13, 13, 13, 15, 15, 16, 16, 16, 19, 19, 20], 36))')