Here is one possible solution:
def _powerset(s):
""" A generator yielding the power set of the items in the sequence s. """
if len(s) <= 1:
yield s # The singleton set
yield () # The empty set
else:
# Loop over the elements in the power set formed from all the items
# after the first in s and yield them with and without this first one.
for item in _powerset(s[1:]):
yield (s[0],) + item
yield item
def powerset(s):
""" A generator returning all the subsets of the set s. """
return set((frozenset(_s) for _s in _powerset(tuple(s))))
S = {'a', 'b', 'c'}
P = powerset(S)
print(P)
# An alternative, nicer way to print the powerset: sorted by cardinality of
# subsets and then by subset elements (assuming they can be ordered)
print(tuple(sorted((tuple(sorted(s)) for s in P), key = lambda s: (len(s),s))))
Note that we have to use frozenset
s if they are to be items in a set
.