This question already has an answer here:
- Powersets in Python using itertools 2 answers
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?
From the recipes section of the itertools documentation:
The fastest way is by using itertools, especially chain and combinations:
If you need a generator just use yield and turn tuples into sets:
and then simply:
I know this is way too old, but I was looking for an answer to the same problem and after a couple hours of non-successful web searching, I came up with my own solution. This is the code:
I took the combinations sample code from itertools doc itertools.combinations and modified it to yield lists instead of tuples. I made annotations when I was trying to figure out how it worked (in order to modify it later), so I'll let them there, just in case someone finds them helpful. Finally, I made all_substes function to find every subset from lengths 1 to r (not including the empty list, so if you need it there just start out as
out = [[]]