Python: powerset of a given set with generators

linkyndy picture linkyndy · Sep 16, 2013 · Viewed 16.7k times · Source

I am trying to build a list of subsets of a given set in Python with generators. Say I have

set([1, 2, 3])

as input, I should have

[set([1, 2, 3]), set([2, 3]), set([1, 3]), set([3]), set([1, 2]), set([2]), set([1]), set([])]

as output. How can I achieve this?

Answer

Pawel Miech picture Pawel Miech · Sep 16, 2013

The fastest way is by using itertools, especially chain and combinations:

>>> from itertools import chain, combinations
>>> i = set([1, 2, 3])
>>> for z in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
    print z 
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
>>> 

If you need a generator just use yield and turn tuples into sets:

def powerset_generator(i):
    for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
        yield set(subset)

and then simply:

>>> for i in powerset_generator(i):
    print i


set([])
set([1])
set([2])
set([3])
set([1, 2])
set([1, 3])
set([2, 3])
set([1, 2, 3])
>>>