variable number of dependent nested loops

余生长醉 提交于 2019-12-07 15:05:04

问题


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:


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)


来源:https://stackoverflow.com/questions/45348038/variable-number-of-dependent-nested-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!