How would you get every possible combination of array below?
Example for array=[1,2,3]
Possible combinations are
1 2 3
1 3 2
2 1 3
2 3 1
3 2 1
3 1 2
CodePudding user response:
Using the itertools
module specifically the permutation
:
from itertools import permutations
print(list(permutations([1, 2, 3])))
CodePudding user response:
Python is easy because lots of library are available. go through the documentation for source code https://docs.python.org/3/library/itertools.html#itertools.permutations
import itertools
a=[1,2,3]
for k in itertools.permutations(a, len(a)):
print(k)
Solution
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)