-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpowerset.py
More file actions
44 lines (33 loc) · 1.04 KB
/
powerset.py
File metadata and controls
44 lines (33 loc) · 1.04 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
""" Subsets possible from a list
"""
def powerset_2(lst):
# the power set of the empty set has one element, the empty set
result = [[]]
for x in lst:
# for every additional element in our set
# the power set consists of the subsets that don't
# contain this element (just take the previous power set)
# plus the subsets that do contain the element (use list
# comprehension to add [x] onto everything in the
# previous power set)
result.extend([subset + [x] for subset in result])
return result
sets = powerset_2(['a', 'b', 'c', 'd'])
print("Total sets ->", len(sets))
for set in sets:
print(set)
def powerset(data):
sets = [[]]
idx = 1
for x in data:
new_sets = [[x]]
for y in data[idx:]:
# new set combinations
new_sets += [set + [y] for set in new_sets]
sets.extend(new_sets)
idx += 1
return sets
sets = powerset(['a', 'b', 'c', 'd'])
print("Total sets ->", len(sets))
for set in sets:
print(set)