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.
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.
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)]
You can use the itertools module:
import itertools
arr = [1,2,3,4]
print [x for x in itertools.permutations(arr)]