-
Notifications
You must be signed in to change notification settings - Fork 19
/
8.4-Power_Set.py
35 lines (28 loc) · 1.03 KB
/
8.4-Power_Set.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
# CTCI 8.4
# Power Set
import copy
#-------------------------------------------------------------------------------
# My Solution
#-------------------------------------------------------------------------------
def power_set(set):
if set is None:
return None
result = []
get_subset(result, set, len(set)-1)
return result
def get_subset(result, set, idx):
if idx == -1:
result.append([])
else:
# This goes all the way down until it reaches the base case []
get_subset(result, set, idx-1)
# Creates a deep copy of the result to append the next character
subsets = copy.deepcopy(result)
for s in subsets:
s.append(set[idx])
# Add all the new elements of powerset (idx+1) to the current result
result.extend(subsets)
#-------------------------------------------------------------------------------
#Testing
#-------------------------------------------------------------------------------
print (power_set(['a', 'b', 'c', 'd', 'e']))