Search code examples
pythonpython-3.xpermutation

Python3 - Permutations for 7 digit number that totals to a number


I need to find a solution for the below problem in Python3. I tried itertools.combinations but not clear on how to do it.

Prepare a 7-digit number that sums to 5. Each digit can be between 0-4 only. Also, there can be repetitions. Valid example numbers are -

[ [2,1,1,0,0,1,0], [3,0,1,0,0,1,0], [0,0,0,4,0,0,1], [1,0,0,3,0,1,0], [1,1,1,1,0,1,0], ...... ]

As you can see, numbers may appear more than once in this list.

How can I create a list of all combinations meeting the criteria above?


Solution

  • This function will find every combination, with repeated combinations, that sum to N:

    from itertools import product
    from typing import List, Tuple
    def perm_n_digit_total(n_digits, total, choices) -> List[Tuple]:
        return list(filter(
            lambda x: sum(x) == total,
            product(choices, repeat=n_digits)
        ))
    

    Example:

    perm_n_digit_total(3, 1, range(4))
    Out[43]: [(0, 0, 1), (0, 1, 0), (1, 0, 0)]
    
    perm_n_digit_total(7, 5, range(4))[::50]
    Out[49]: 
    [(0, 0, 0, 0, 0, 0, 5),
     (0, 0, 0, 3, 1, 1, 0),
     (0, 0, 2, 0, 3, 0, 0),
     (0, 1, 0, 1, 3, 0, 0),
     (0, 2, 0, 0, 1, 0, 2),
     (0, 4, 1, 0, 0, 0, 0),
     (1, 0, 1, 1, 1, 0, 1),
     (1, 1, 1, 1, 1, 0, 0),
     (2, 0, 1, 0, 0, 2, 0),
     (3, 1, 0, 0, 0, 1, 0)]