0

For example I have an array, that looks like this [[1, 2, 3], [4, 5], [7, 8, 9]]

My mission is too show all combinations in the array, like this:

1-4-7, 1-4-8, 1-4-9

1-5-7, 1-5-8, 1-5-9

2-4-7, 2-4-8, 2-4-9

2-5-7, 2-5-8, 2-5-9

3-4-7, 3-4-8, 3-4-9

3-5-7, 3-5-8, 3-5-9

I have seen many different solutions, like this - How to get all possible combinations of a list’s elements?, but it isn't for me

Add-on: Array can't be mutated

rawrex
  • 4,044
  • 2
  • 8
  • 24
9gress0r
  • 13
  • 1

2 Answers2

4

Since you are looking for the cartesian product of the lists, use itertools.product:

from itertools import product

data = [[1, 2, 3], [4, 5], [7, 8, 9]]

for p in product(*data):
    print("-".join(map(str, p)))

1-4-7
1-4-8
1-4-9
1-5-7
# ...
3-4-9
3-5-7
3-5-8
3-5-9
user2390182
  • 72,016
  • 6
  • 67
  • 89
-1

Something like the following should work, if you don't want to use itertools like the linked answer did:

First, maintain a list of indices, let's call it positions, that represent what elements you're currently looking at in each of the inner lists, and initialise all of these indices to 0. In your example given this would look like [0,0,0]

Print out / store the combination that results from these indices. Here that would be 1, 4, 7.

Increment the last index in the list. If this index is now the size of the list it corresponds to (in the example, for the last index, that would be 3, for the second last, 2, etc.) then reset it to 0 and increment the next index along instead. Do this check for all the values in positions

Repeat this process, printing out / storing the resulting combination each time, until the very first index in positions reaches the size of the first list in your list of lists, at which point you're done