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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With