In this post, you will learn a python program to find the power set of the given set with a detailed explanation but before writing a program let us understand what is power set.
What is Power Set?
All possible subsets of a given set including an empty set are known as a power set.
For Example:
NOTE: If set A has n elements then the power set of A has 2n elements.
So let us write a Power Set Program in Python but before we jump into the program you should know about:
Source Code
# Input size of the set
size_of_set = int(input('Enter size of set: '))
# Input elements of the set (user input)
set1 = [input(f"Enter {i+1} element: ") for i in range(size_of_set)]
# Initialize the result with an empty subset
result = [[]]
# Generate all subsets
for i in set1:
n = len(result)
for j in range(n):
r = result[j] + [i]
result.append(r)
# Print all subsets
for element in result:
print(element)
Output
Enter size of set: 3
enter 1 element: a
enter 2 element: b
enter 3 element: c
[]
['a']
['b']
['a', 'b']
['c']
['a', 'c']
['b', 'c']
['a', 'b', 'c']
Power Set Program in Python Using Function
Few programming concepts you should know before writing this program:
Source Code
def power_set(my_set):
result = [[]]
for i in my_set:
n = len(result)
for j in range(n):
r = result[j] + [i]
result.append(r)
return result
size_of_set = int(input('Enter size of set: '))
set1 = [input(f"enter {i+1} element: ") for i in range(size_of_set)]
result = power_set(set1)
for element in result:
print(element)
Output
Enter size of set: 4
enter 1 element: 1
enter 2 element: 2
enter 3 element: 3
enter 4 element: 4
[]
['1']
['2']
['1', '2']
['3']
['1', '3']
['2', '3']
['1', '2', '3']
['4']
['1', '4']
['2', '4']
['1', '2', '4']
['3', '4']
['1', '3', '4']
['2', '3', '4']
['1', '2', '3', '4']