Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Permutations Limited to only increasing numbers [duplicate]

I'm trying to create a function that will produce all permutations of a list but limited to only sets of len(n) and only increasing from left to right. For instance, if I have 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 plenty of variations of permutation functions but none with this kind of restriction.

like image 614
happyhippo83 Avatar asked Mar 10 '23 04:03

happyhippo83


1 Answers

From itertools docs:

Combinations are emitted in lexicographic sort order. So, if the input iterable is sorted, the combination tuples will be produced in sorted order.

So if you have a sorted list, then using itertools.combinations you'll get your desired result. If not, you can call sorted() first.

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)]
like image 117
ayhan Avatar answered Apr 06 '23 21:04

ayhan