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])
>>>
python itertools powerset recipe
? That's got exactly what you're asking... and then on docs.python.org/2/library/itertools.html - search forpowerset
... – Programmechain.from_iterable
you in effect have a generator. What is there that you can't easily adapt for whatever your requirement is ?return imap(set, chain.from_iterable(...))
? – Programme