How to Generate All Possible Subsets of a Set in Python?

83 views

How to Generate All Possible Subsets of a Set in Python?

How to Generate All Possible Subsets of a Set in Python?

How can you generate all possible subsets (powerset) of a set in Python?

solveurit24@gmail.com Changed status to publish February 20, 2025
0

You can use the itertools module to generate subsets:

import itertools

def powerset(s):
    return [subset for l in range(len(s)+1) for subset in itertools.combinations(s, l)]

s = {1, 2, 3}
print(powerset(s))

solveurit24@gmail.com Changed status to publish February 20, 2025
0