Generating all possible combinations of a list, "itertools.combinations" misses some results Generating all possible combinations of a list, "itertools.combinations" misses some results python python

Generating all possible combinations of a list, "itertools.combinations" misses some results


Use itertools.permutations:

>>> import itertools>>> stuff = [1, 2, 3]>>> for L in range(0, len(stuff)+1):        for subset in itertools.permutations(stuff, L):                print(subset)...         ()(1,)(2,)(3,)(1, 2)(1, 3)(2, 1)(2, 3)(3, 1)....

Help on itertools.permutations:

permutations(iterable[, r]) --> permutations objectReturn successive r-length permutations of elements in the iterable.permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)


You can generate all the combinations of a list in python using this simple code

import itertoolsa = [1,2,3,4]for i in xrange(1,len(a)+1):   print list(itertools.combinations(a,i))

Result:

[(1,), (2,), (3,), (4,)][(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)][(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)][(1, 2, 3, 4)]


Are you looking for itertools.permutations instead?

From help(itertools.permutations),

Help on class permutations in module itertools:class permutations(__builtin__.object) |  permutations(iterable[, r]) --> permutations object |   |  Return successive r-length permutations of elements in the iterable. |   |  permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)

Sample Code :

>>> from itertools import permutations>>> stuff = [1, 2, 3]>>> for i in range(0, len(stuff)+1):        for subset in permutations(stuff, i):               print(subset)()(1,)(2,)(3,)(1, 2)(1, 3)(2, 1)(2, 3)(3, 1)(3, 2)(1, 2, 3)(1, 3, 2)(2, 1, 3)(2, 3, 1)(3, 1, 2)(3, 2, 1)

From Wikipedia, the difference between permutations and combinations :

Permutation :

Informally, a permutation of a set of objects is an arrangement of those objects into a particular order. For example, there are six permutations of the set {1,2,3}, namely (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2), and (3,2,1).

Combination :

In mathematics a combination is a way of selecting several things out of a larger group, where (unlike permutations) order does not matter.