-1

I have a project that needs to run through all combinations of a list with set numbers in a loop.

e.g.

code = [4,3,2,1]
code = [4,3,1,2]
code = [4,2,1,3]
.
.
.

I have tried to make a long list of numbers to make some sort of manual

e.g.

code = [4,3,2,1]
manual = [1,2,1,2,1,3,1,2,1,2,1,3,1,2,1,2,1,3,1,2,1,2,1,0]
for m in manual:
    print(code)
    if m == 1:
        code[-1], code[-2] = code[-2], code[-1]
    elif m == 2:
        code[-1], code[-3] = code[-3], code[-1]
    elif m == 3:
        code[-1], code[-2] , code[-3] , code[-4] = code[-4], code[-3] , code[-2] , code[-1]

This works, but the manual gets very large if I have a large number of code combinations lists.

Is there a better way of doing it - or should I just keep going with the manual version?

I mainly write in python but can also read many other languages, so if you want to write in another, I can understand that too

Leonardus Chen
  • 1,103
  • 6
  • 20
KrissKloss
  • 61
  • 3

2 Answers2

2

For this, you can use the permutations functions provided in the standard library, if you are using Python 2.6 and above, or you are using Python 3.

import itertools
permutations = list(itertools.permutations([1, 2, 3, 4]))

for i in list(perm):  
  print(i)

Which results in:

(1, 2, 3, 4)
(1, 2, 4, 3)
(1, 3, 2, 4)
(1, 3, 4, 2)
(1, 4, 2, 3)
(1, 4, 3, 2)
(2, 1, 3, 4)
(2, 1, 4, 3)
(2, 3, 1, 4)
(2, 3, 4, 1)
(2, 4, 1, 3)
(2, 4, 3, 1)
(3, 1, 2, 4)
(3, 1, 4, 2)
(3, 2, 1, 4)
(3, 2, 4, 1)
(3, 4, 1, 2)
(3, 4, 2, 1)
(4, 1, 2, 3)
(4, 1, 3, 2)
(4, 2, 1, 3)
(4, 2, 3, 1)
(4, 3, 1, 2)
(4, 3, 2, 1)
Lee Boon Kong
  • 1,007
  • 1
  • 8
  • 17
1

If I understand your question correctly, itertools.permutations should do the trick:

from itertools import permutations

code = [4,3,2,1]
for perm in permutations(code):
    print(perm)
# (4, 3, 2, 1)
# (4, 3, 1, 2)
# (4, 2, 3, 1)
# ...
ssp
  • 1,666
  • 11
  • 15