variable number of dependent nested loops

2019-05-10 04:48发布

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?

1条回答
Evening l夕情丶
2楼-- · 2019-05-10 05:26

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)
查看更多
登录 后发表回答