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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With