简体   繁体   English

Python 递归 - 求和堆栈

[英]Python recursion - sum stack

I am trying to retrieve elements in a recursion that sum-up to a specific value (value of 9 in this case).我试图在递归中检索总和为特定值(在本例中为 9 的值)的元素。

In the simplified example in the below image, where I have 3 branches (with the values 3, 4 and 5), and where the maximum possible sum is 9, I would expect the following output:在下图中的简化示例中,我有 3 个分支(值为 3、4 和 5),并且最大可能总和为 9,我希望得到以下输出:

[3,3,3] (= 9)
[3,4]   (= 7)
[3,5]   (8)
[4,3]   (7)
[4,4]   (8)
[4,5]   (9)
[5,3]   (8)

在此处输入图片说明 My output in the code below, however, is quite different:然而,我在下面代码中的输出却大不相同:

i =  [3, 3, 3]
i =  [3, 3, 3]
i =  [3, 3, 3]
i =  [3, 3]
i =  [3, 3]
i =  [3, 3]
i =  [3]
i =  [3, 4]
i =  [3, 4]
i =  [3, 4]
i =  [3]
i =  [3, 5]
i =  [3, 5]
i =  [3, 5]
i =  [3]

I know I can use itertools to get a similar output, but my actual code is more complex than this one and I cannot use iterools there.我知道我可以使用 itertools 来获得类似的输出,但我的实际代码比这个更复杂,我不能在那里使用 iterools。 This is my current code:这是我当前的代码:

import copy
maximum_sum = 9
branches = [3,5]
ar = []
big_ar = []

def recurse(summary, index):
    if summary + branches[index] <= maximum_sum:   
        summary += branches[index]
        ar.append(branches[index])

        for i in range(len(branches)):  
            recurse(summary, i)
            my_ar = copy.deepcopy(ar)
            big_ar.append(my_ar)
        del ar[-1]
    return (big_ar)

all_clusters = recurse(0, 0)
for i in all_clusters:
    print ('i = ', i)
maxsum = 9
branches = [3, 4, 5]

def recurse(maxsum):
    if maxsum < min_branch:
        yield []
    for b in branches:
        if maxsum >= b:
             for v in recurse(maxsum - b):
                   yield [*v, b]
        else:
            return

for i in recurse(9):
    print ('i = ', i)

Solution - this is what I was trying to achieve.解决方案 - 这就是我想要实现的目标。 Quick and dirty but it works:又快又脏,但它有效:

import copy
maximum_sum = 9
branches = [3,4,5]
ar = []
sum_ar = []

def recurse(summary, index):
    if summary + branches[index] <= maximum_sum:   
        summary += branches[index]
        ar.append(branches[index])

        for i in range(len(branches)): 
            recurse(summary, i)

        if summary + branches[index] > maximum_sum:    
            my_ar = copy.deepcopy(ar)
            sum_ar.append(my_ar)
        del ar[-1]
    return (sum_ar)

for i in range(len(branches)):
    all_clusters = recurse(0, i)

for i in all_clusters:
print ('i = ', i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM