Search code examples
pythonnested-loopsinteger-partition

variable number of dependent nested loops


Given two integers n and d, I would like to construct a list of all nonnegative tuples of length d that sum up to n, including all permutations. This is similar to the integer partitioning problem, but the solution is much simpler. For example for d==3:

[
    [n-i-j, j, i]
    for i in range(n+1)
    for j in range(n-i+1)
]

This can be extended to more dimensions quite easily, e.g., d==5:

[
    [n-i-j-k-l, l, k, j, i]
    for i in range(n+1)
    for j in range(n-i+1)
    for k in range(n-i-j+1)
    for l in range(n-i-j-l+1)
]

I would now like to make d, i.e., the number of nested loops, a variable, but I'm not sure how to nest the loops then.

Any hints?


Solution

  • Recursion to the rescue: First create a list of tuples of length d-1 which runs through all ijk, then complete the list with another column n-sum(ijk).

    def partition(n, d, depth=0):
        if d == depth:
            return [[]]
        return [
            item + [i]
            for i in range(n+1)
            for item in partition(n-i, d, depth=depth+1)
            ]
    
    
    # extend with n-sum(entries)
    n = 5
    d = 3
    lst = [[n-sum(p)] + p for p in partition(n, d-1)]
    
    print(lst)