how to get the power set of a set in python

There are multiple ways to get the power set of a set in Python. Here are two commonly used approaches:

Using Recursion

main.py
def get_power_set(s):
    # Base case: return the empty set
    if not s:
        return {frozenset()}
    
    # Recursive case: build power set of the rest of the set
    rest = get_power_set(s[1:])
    
    # Add the first element of the set to each subset in the power set of the rest of the set
    return rest.union({subset.union({s[0]}) for subset in rest})
365 chars
11 lines

This approach recursively builds the power set by first returning the empty set for the base case, and then for each recursive call, building the power set of the rest of the set and adding the first element of the set to each subset in the power set of the rest of the set.

Using itertools

main.py
import itertools

def get_power_set(s):
    return {frozenset(subset) for i in range(len(s)+1) for subset in itertools.combinations(s, i)}
139 chars
5 lines

This approach uses the built-in itertools module to generate all possible combinations of the elements of the set. It then converts these combinations to sets and returns them as a set of sets (a.k.a. a power set).

gistlibby LogSnag