-2

Say you got an array of 4 numbers. What is the best way to go through all the possible combinations? A start of the combinations would be:

1,2,3,4

1,2,4,3

1,3,2,4

1,3,4,2

1,4,2,3

2,1,3,4

etc.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Raymond
  • 125
  • 1
  • 7
  • 5
    Your answer is probably here: http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list – mrcheshire May 13 '16 at 21:00
  • @mrcheshire not exactly, what I want is all combinations of the 4 numbers in different orders. In that post they explain how every combination of those 4 numbers are listed, doesn't matter the order. So 1,2,3,4 is the same as 1,3,2,4. Which I don't want to be the case. – Raymond May 13 '16 at 21:05

2 Answers2

2

itertools.permutations is just what you're looking for:

>>> from itertools import permutations
>>> [i for i in permutations(range(1, 5), 4)]
[(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)]

EDIT:
Or, as @wflynny pointed out, you can save the list comprehension by just calling list's constructor:

>>> from itertools import permutations
>>> list(permutations(range(1, 5), 4))
[(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)]
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

You can use the itertools module:

import itertools
arr = [1,2,3,4]
print [x for x in itertools.permutations(arr)]
drewyupdrew
  • 1,549
  • 1
  • 11
  • 16