Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading