Home > Back-end >  How do I get all n! combinations of possible lists that can be created from numbers 1 to n?
How do I get all n! combinations of possible lists that can be created from numbers 1 to n?

Time:10-09

It's kind of difficult to explain, so let me give an example:

For n=3, I want to make all lists:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

How do I implement a function that each time returns the next list? (or one that returns a list of all possible lists?)

CodePudding user response:

What you are looking for are the permutations of range(1, n 1):

from itertools import permutations

n = 3
for permutation in permutations(range(1, n   1)):
  print(permutation)

range(1, n 1) gives you the interval [1, n], as range creates half open intervals. itertools.permutations takes all those values and gives you all possible combinations.

If you have the memory for it (n! gets big pretty fast), you can collect them all into a list:

output = list(permutations(range(1, n   1)))
  • Related