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:

  1. for-loop
  2. python list &
  3. nested list in python.

Source Code

size_of_set = int(input('Enter size of set: '))

set1 = [input(f"enter {i+1} element: ") for i in range(size_of_set)]

result = [[]]

for  i in set1:
    n = len(result)

    for j in range(n):
        r = result[j] + [i]
        result.append(r)
    
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:

  1. for-loop
  2. python list
  3. nested list in python &
  4. Function in python.

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']

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment