Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permutations in a list

I have a list containing n integers. The ith element of the list a, a[i], can be swapped into any integer x such that 0 ≤ x ≤ a[i]. For example if a[i] is 3, it can take values 0, 1, 2, 3.

The task is to find all permutations of such list. For example, if the list is

my_list = [2,1,4]

then the possible permutations are:

[0,0,0], [0,0,1], ... [0,0,4],
[0,1,0], [0,1,1], ... [0,1,4],
[1,0,0], [1,0,1], ... [1,0,4],
[1,1,0], [1,1,1], ... [1,1,4],
[2,0,0], [2,0,1], ... [2,0,4],
[2,1,0], [2,1,1], ... [2,1,4]

How to find all such permutations?


1 Answers

you could use a comibation of range to get all the 'valid' values for each element of the list and itertools.product:

import itertools

my_list = [2,1,4]

# get a list of lists with all the possible values
plist = [list(range(y+1)) for y in my_list]

#
permutations = sorted(list(itertools.product(*plist)))

more on itertools product see e.g. here on SO or the docs.

like image 88
FObersteiner Avatar answered Nov 02 '25 23:11

FObersteiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!