Python Permutations Limited only by increasing the number

I am trying to create a function that will do all the permutations in a list, but is limited to only sets len(n)

and only grows from left to right. For example, if I have a list l = [2,4,6,8,10]

and n = 3

, the results should be

[2,4,6],
[2,4,8],
[2,4,10],
[2,6,8],
[2,6,10],
[2,8,10],
[4,6,8],
[4,6,10],
[6,8,10]

      

I've seen many variations on permutation functions, but no such type of limitation.

+3


source to share


1 answer


From the itertools docs :

The combinations are emitted in lexicographic sort order. Thus, if the sort of the input iterations is sorted, the combination tuples will be created in sorted order.



So, if you have a sorted list, then using itertools.combinations

will get the desired result. If not, you can call first sorted()

.

lst = range(2, 11, 2)

list(itertools.combinations(lst, 3))
Out: 
[(2, 4, 6),
 (2, 4, 8),
 (2, 4, 10),
 (2, 6, 8),
 (2, 6, 10),
 (2, 8, 10),
 (4, 6, 8),
 (4, 6, 10),
 (4, 8, 10),
 (6, 8, 10)]

      

+6


source







All Articles