-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathPowerSet.py
119 lines (94 loc) · 2.66 KB
/
PowerSet.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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# http://www.geeksforgeeks.org/power-set/
def power_set(array: list, n: int):
# Len of PowerSet = 2^n
max_len = pow(2, n)
powerSet = []
for num in range(max_len):
l = []
# 0 to n
for i in range(n):
if (num & (1 << i)):
l.append(array[i])
powerSet.append(l)
return powerSet
# main
if __name__ == "__main__":
array = input().split()
n = len(array)
powerSet = power_set(array, n)
# Sort by length
powerSet = sorted(powerSet, key=len)
print("Power Set :")
print(powerSet)
"""
Input Explanation :
- List of numbers
Input :
1 2 3
Output :
Power Set :
[[], ['1'], ['2'], ['3'], ['1', '2'], ['1', '3'], ['2', '3'], ['1', '2', '3']]
"""
'''
Power Set Power set P(S) of a set S is the set of all subsets of S. For example S = {a, b, c} then
P(s) = {{}, {a}, {b}, {c}, {a,b}, {a, c}, {b, c}, {a, b, c}}.
If S has n elements in it then P(s) will have 2^n elements
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
Algorithm:
Input: Set[], set_size
1. Get the size of power set
powet_set_size = pow(2, set_size)
2 Loop for counter from 0 to pow_set_size
(a) Loop for i = 0 to set_size
(i) If ith bit in counter is set
Print ith element from set for this subset
(b) Print seperator for subsets i.e., newline
Example:
Set = [a,b,c]
power_set_size = pow(2, 3) = 8
Run for binary counter = 000 to 111
Value of Counter Subset
000 -> Empty set
001 -> a
010 -> b
011 -> ab
100 -> c
101 -> ac
110 -> bc
111 -> abc
Program:
#include <stdio.h>
#include <math.h>
void printPowerSet(char *set, int set_size)
{
/*set_size of power set of a set with set_size
n is (2**n -1)*/
unsigned int pow_set_size = pow(2, set_size);
int counter, j;
/*Run from counter 000..0 to 111..1*/
for(counter = 0; counter < pow_set_size; counter++)
{
for(j = 0; j < set_size; j++)
{
/* Check if jth bit in the counter is set
If set then pront jth element from set */
if(counter & (1<<j))
printf("%c", set[j]);
}
printf("\n");
}
}
/*Driver program to test printPowerSet*/
int main()
{
char set[] = {'a','b','c'};
printPowerSet(set, 3);
getchar();
return 0;
}
Run on IDE
Time Complexity: O(n2^n)
Refer Power Set in Java for implementation in Java and more methods to print power set.
References:
http://en.wikipedia.org/wiki/Power_set
'''