How do I generate
[(0,), (1,), (2,), (0,1), (0,2), (1,2), (0,1,2)]
programmatically (that is, without writing everything out by hand)? That is, a list of all nonempty subtuples of the tuple (0,1,2).
(Note this is not asking for subsets but subtuples.)
>>> 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 out the documentation
You can use the powerset() recipe and remove the 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))
as follows:
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)]
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