How to Create a Powerset in Python?

Estimated read time 1 min read

You can create a powerset of a given set in Python using recursion. Here’s an example code snippet:

def powerset(s):
    if not s:
        return [[]]
    else:
        result = []
        for subset in powerset(s[1:]):
            result.append(subset)
            result.append([s[0]] + subset)
        return result

# Example usage:
my_set = [1, 2, 3]
print(powerset(my_set))

In this example, we define a powerset function that takes a list s as input and returns the powerset of s.

If s is an empty list, we return a list containing an empty list, which represents the empty set. Otherwise, we recursively call the powerset function with the first element of s removed. We iterate over the subsets returned by the recursive call, and for each subset, we append it to the result list and also append a new subset that includes the first element of s.

Finally, we return the result list containing all subsets of s.

We test the function by creating a list my_set and calling powerset(my_set) to print the powerset of my_set.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply