Subsets of a tuple
3 answers
>>> from itertools import combinations
>>> t = (0, 1, 2)
>>> print [subset for r in range(1,4) for subset in itertools.combinations(t,r)]
[(0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]
Itertools is a powerful resource. You should check the documentation
+5
source to share
You can use powerset()
recipe and delete empty set:
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))
in the following way:
In [3]: [ss for ss in powerset([0,1,2]) if ss]
Out[3]: [(0,), (1,), (2,), (0, 1), (0, 2), (1, 2), (0, 1, 2)]
+4
source to share
What you want is basically a poweret, but no empty set. Modifying the recipe from the python itertools page , start with the size of the combinations 1
:
from itertools import combinations, chain
def almost_powerset(seq):
return list(chain.from_iterable(combinations(seq, r)
for r in range(1, len(seq)+1)))
and then just pass in your sequence
lst = [0, 1, 2]
res = almost_powerset(lst)
This generates all combinations of size 1, then size 2, and so on, down to the total length of your sequence, and then uses chain
them to join them.
+2
source to share