Reputation: 15682
I have a sequence of consecutive integers, for example [1, 2, 3]
. I'd like to create an iterator that goes through all the subsets of the set. In this case [], [1],...,[1,2,3]
. How could I do this?
Upvotes: 10
Views: 8149
Reputation: 119
Here's another simple way of doing that without extra libraries
set = [1,2,3]
subsets = [[]]
for el in set:
for i in range(len(subsets)):
subsets += [subsets[i]+[el]]
print(subsets)
The output:
[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
Or even simpler with the help of list comprehension
set = [1,2,3]
subsets = [[]]
for el in set:
subsets += [s+[el] for s in subsets]
print(subsets)
Upvotes: 2
Reputation: 82470
The itertools
documentation contains a recipe for this construction under the name powerset
, if that's what you need.
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
Upvotes: 15