How to Calculate the Power Set of a Set in Python

from itertools import chain, combinations

def power_set(some_set):
    return list(chain.from_iterable(combinations(some_set, r) for r in range(len(some_set) + 1)))

original_set = {1, 2, 3}
all_subsets = power_set(original_set)
print(f"Power set of {original_set}: {all_subsets}")

Output:

Power set of {1, 2, 3}: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

Leave a Comment

Your email address will not be published.