-4

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
Suchy
  • 11
  • 2
  • 2
    itertools.permutations – Dani Mesejo Oct 30 '21 at 11:05
  • What did you try or research for this? – Daniel Hao Oct 30 '21 at 11:08
  • Side note `array` is different than `list`. Read this https://stackoverflow.com/questions/176011/python-list-vs-array-when-to-use if interested to know more. – Daniel Hao Oct 30 '21 at 11:27
  • Those are permutations, not combinations. Also, you should describe what you mean by "without repetition". Is that a condition of your input (i.e. the list will not contain repetitions) or a filter on the output (i.e. the permutations should not have repeated values even when the list does contain duplicates) ? – Alain T. Oct 30 '21 at 19:04

2 Answers2

1

Using the itertools module specifically the permutation:

from itertools import permutations

print(list(permutations([1, 2, 3])))
CodeCop
  • 1
  • 2
  • 15
  • 37
1

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)
Dharman
  • 30,962
  • 25
  • 85
  • 135