Search code examples
python-3.xcombinationspython-itertools

Python3 itertools permutation & combination question


I want to build a combination of all 7-digit numbers possible from a set of numbers following the rules below.

  1. Each digit can only hold values as shown below from python3 list variables N1-N7 as an example.
N1 = [0,1,2]
N2 = [0,1] 
N3 = [0,1,2] 
N4 = [0] 
N5 = [1] 
N6 = [0,1] 
N7 = [0]
  1. Total of all the digits in any of the 7-digit numbers should be exactly 5. Valid examples of the 7-digit numbers.
0120110,1110110,1120100,2020100

Solution

  • You can use the Cartesian product method of the itertools library,
    Basically it generates all possible combinations of each group.

    For example,

    import itertools
    
    list(itertools.product([1,2], ['a', 'b']))
    

    Should return:

    [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
    

    Applying it to your constraint that we need to pick the first digit from N1, second digit from N2 etc...

    result = [''.join(map(str, combination)) for combination in itertools.product(N1, N2, N3, N4, N5, N6, N7)]
    

    This does not enforce that the sum will be equal to five, so we can add it with a simple if statement:

    result = [''.join(map(str, cartesian_product)) for cartesian_product in itertools.product(N1, N2, N3, N4, N5, N6, N7) if sum(cartesian_product) == 5]
    

    Resulting in:

    ['0120110', '1020110', '1110110', '1120100', '2010110', '2020100', '2100110', '2110100']