Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtuples of a tuple [duplicate]

Tags:

python

tuples

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.)

like image 491
Bjørn Kjos-Hanssen Avatar asked Sep 05 '26 14:09

Bjørn Kjos-Hanssen


2 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 out the documentation

like image 90
David Greydanus Avatar answered Sep 08 '26 03:09

David Greydanus


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)]
like image 40
xnx Avatar answered Sep 08 '26 04:09

xnx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!