Skip to content

Commit 9b4ba8c

Browse files
committed
Add Power set of a given set Algorithm
1 parent 3418857 commit 9b4ba8c

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'''
2+
Print all subsets (power set) of a given set
3+
4+
The input for this problem will be an array of numbers representing a set, which only contains unique numbers,
5+
and your goal is to print every possible set combination, otherwise known as the power set.
6+
7+
For example:
8+
input set = [1, 2, 3]
9+
power set = [ [], [1], [2], [3], [1, 2], [2, 3], [1, 3] [1, 2, 3] ]
10+
11+
The power set contains every possible combination of numbers.
12+
It also includes the empty set which contains no numbers from the original set.
13+
14+
https://coderbyte.com/algorithm/print-all-subsets-given-set
15+
'''
16+
17+
18+
'''
19+
There will be 2N possible combinations of a set of length N,
20+
because every element can either be in the set or not, which gives us 2 possibilities,
21+
and we do this for N numbers, giving us 2 * 2 * 2 ... = 2^N.
22+
23+
(1) Loop from 0 to 2^N
24+
(2) For each number get the binary representation of the number, example: 3 = 011
25+
(3) Determine from the binary representation whether or not to include a number from the set, example: 011 = [exclude, include, include]
26+
'''
27+
def power_set(set):
28+
response = []
29+
30+
# loop from 0 to 2^N
31+
for x in range(0, pow(2, len(set))):
32+
print('\nnumber:', x, '|| binary:', bin(x))
33+
34+
# get the binary representation of the number
35+
# and put each digit in a list position
36+
binary = list(bin(x))
37+
38+
# delete the first two characters which are '0b'
39+
del binary[0:2]
40+
41+
# fill the list with left zeros
42+
# padding the binary number so 1 becomes 001 for example
43+
while len(binary) < len(set):
44+
binary.insert(0, 0)
45+
46+
# convert all the elements to integers
47+
binary = list(map(int, binary))
48+
print('binary list:', binary)
49+
50+
# determine from the binary representation whether or not to include a number from the set
51+
# building the combination that matches the 1's in the binary number
52+
res = []
53+
for index in range(len(binary)):
54+
if (binary[index]):
55+
res.append(set[index])
56+
57+
# add the new combination to the response
58+
response.append(res)
59+
60+
response.sort()
61+
return response
62+
63+
64+
print(' Input Set: [1, 2, 3]\n Output:', power_set([1, 2, 3]))

0 commit comments

Comments
 (0)