How to Create a Power Set in Python?

Estimated read time 1 min read

In Python, you can create a power set of a given set using the itertools library. Here’s an example code snippet:

import itertools

def power_set(s):
    power_set = []
    for i in range(len(s)+1):
        for subset in itertools.combinations(s, i):
            power_set.append(subset)
    return power_set

# Example usage:
my_set = {1, 2, 3}
print(power_set(my_set))

In this example, we define a power_set function that takes a set s as input and returns the power set of s. We initialize an empty list power_set to store the subsets. We then use two nested loops to generate all possible combinations of the elements of s. The outer loop iterates over all possible subset sizes from 0 to the size of s, while the inner loop generates all combinations of elements of the current subset size using the itertools.combinations() function. Each subset is then appended to the power_set list.

Finally, we test the function by creating a set my_set and calling power_set(my_set) to print the power set of my_set.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply