forked from jwasham/practice-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubsets.py
More file actions
65 lines (53 loc) · 1.22 KB
/
subsets.py
File metadata and controls
65 lines (53 loc) · 1.22 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
Generates all subsets
"""
import sys
# def is_solution(k, n):
# return k == n
#
#
# def construct_candidates():
# return [0, 1]
#
#
# def process_solution(working_set):
# global solutions
#
# s = {k for k in working_set if working_set[k] == 1}
# solutions.append(s)
#
#
# def backtrack(working_set, k, n):
#
# if is_solution(k, n):
# process_solution(working_set)
# else:
# k += 1
# candidates = construct_candidates()
# for i in candidates:
# working_set[k] = i
# backtrack(working_set, k, n)
def backtrack_compact(working_set, k, n):
global solutions
if k == n:
s = {k for k in working_set if working_set[k] == 1}
solutions.append(s)
else:
k += 1
for i in [0, 1]:
working_set[k] = i
backtrack_compact(working_set, k, n)
def main():
if 0 < 1 < len(sys.argv):
n = int(sys.argv[1])
else:
exit('Usage: subsets.py number')
global solutions
solutions = []
# backtrack({}, 0, n)
# print(solutions)
backtrack_compact({}, 0, n)
print(solutions)
print('Number of subsets: {}'.format(len(solutions)))
if __name__ == '__main__':
main()