Subsets of a tuple

How to create

[(0,), (1,), (2,), (0,1), (0,2), (1,2), (0,1,2)]

      

programmatically (that is, without manually writing everything down)? That is, a list of all non-empty subsets of the tuple (0,1,2)

.

(Note that this is not a definition of subsets, but subsets.)

+3


source to share


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


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


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







All Articles