Given a set
{0, 1, 2, 3}
How can I produce the subsets:
[set(),
{0},
{1},
{2},
{3},
{0, 1},
{0, 2},
{0, 3},
{1, 2}
I just wanted to provide the most comprehensible solution, the anti code-golf version.
from itertools import combinations
l = ["x", "y", "z", ]
def powerset(items):
combo = []
for r in range(len(items) + 1):
#use a list to coerce a actual list from the combinations generator
combo.append(list(combinations(items,r)))
return combo
l_powerset = powerset(l)
for i, item in enumerate(l_powerset):
print "All sets of length ", i
print item
The results
All sets of length 0
[()]
All sets of length 1
[('x',), ('y',), ('z',)]
All sets of length 2
[('x', 'y'), ('x', 'z'), ('y', 'z')]
All sets of length 3
[('x', 'y', 'z')]
For more see the itertools docs, also the wikipedia entry on power sets