0

I want to be able to produce all possible permutations of an array of n elements, where each one of the n elements can take specific discrete values.

For example, lets say I want to create all possible (27) permutations of an array of 3 numbers, where:

The first number can be either 1,3 or 4 The second number can be either 0,2 or 3 The third number can be either 1,2 or 5

The answer will be (1,0,1) (1,2,1) (3,0,1) (3,2,1) (3,2,2) ... etc

Is anybody kind enough to tell me how to do this in Python? What I want is to provide as inputs the possible choices for each number and then the algorithm will produce all possible permutations

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Did you try [this](https://www.geeksforgeeks.org/generate-all-the-permutation-of-a-list-in-python/) – Shisui Otsutsuki Aug 30 '22 at 08:40
  • 1
    Use [itertools.product](https://docs.python.org/3/library/itertools.html#itertools.product). For example: `ret = list(product((1,3,4), (0,2,3), (1,2,5)))` – HALF9000 Aug 30 '22 at 08:43
  • Welcome to Stack Overflow. The reason you have been having difficulty [finding](https://meta.stackoverflow.com/questions/261592) an answer is that what you want is **not called a "permutation"**. Please see the linked duplicate. – Karl Knechtel Aug 30 '22 at 08:46

1 Answers1

0

From your description, it looks like you are looking for the cartesian product of the three sets of numbers. The itertools module has a product function to generate the cartesian product -

from itertools import product
l1 = [1, 3, 4]
l2 = [0, 2, 3]
l3 = [1, 2, 5]
list(product(l1, l2, l3))

Output

print(len(list(product(l1, l2, l3))))
# 27
Mortz
  • 4,654
  • 1
  • 19
  • 35