2

Let us suppose I have 3 lists with each of them has random numbers ranging from (0-9)

digit_0 = [0, 1, 2, 3, 5, 8]
digit_1 = [1, 2, 3, 8, 9]
digit_2 = [3, 4, 6, 7]

I want to create all the possible numbers for 3 -digit number ABC, such that A can only take values from digit_0, B can only from digit_1 and C can only from digit_2 arrays

The simplest solution seems to be creating 3 loops

for A in digit_0:
    for B in digit_1:
        for C in digit_2:

However, I am wondering is there a more effective solution ?

Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
Arman Çam
  • 115
  • 7

2 Answers2

3

Use itertools.product:

from itertools import product

digit_0 = (0, 1, 2, 3, 5, 8)
digit_1 = (1, 2, 3, 8, 9)
digit_2 = (3, 4, 6, 7)

for digits in product(digit_0, digit_1, digit_2):
    print(''.join(map(str, digits)), end=' ')

Output:

013 014 016 017 023 024 026 027 033 034 036 037 083 084 086 087 093 094 096 097 113 114 116 117 

It would be even better to put your tuples in a list, rather than giving them ressembling names:

from itertools import product

digit_choices = [(0, 1, 2, 3, 5, 8), (1, 2, 3, 8, 9), (3, 4, 6, 7)]

for digits in product(*digit_choices):
    print(''.join(map(str, digits)))

and this will make it easy to generate combinations with any number of digits.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

Use list comprehension, as an alternative to itertools.product:

digit_0 = (0, 1, 2, 3, 5, 8)
digit_1 = (1, 2, 3, 8, 9)
digit_2 = (3, 4, 6, 7)
print([f"{d0}{d1}{d2}" for d0 in digit_0 for d1 in digit_1 for d2 in digit_2])

Output:

['013', '014', '016', ..., '896', '897']
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47