首页 > 解决方案 > 从递归中取出列表

问题描述

基本情况下的临时是我需要的答案。它应该被附加到最后。但我最终得到了空列表的列表。有什么建议吗?

def recur(st,end,a,temp,k,final):
    if sum(temp) == k:
        final.append(temp)
        print(temp)
        return
    if sum(temp)>k:
        return
    if st==end-1:
        return
    st+=1
    temp.append(a[st])
    recur(st,end,a,temp,k,final)
    temp.pop()
    recur(st,end,a,temp,k,final)
for _ in range(int(input())):
    a = list(map(int,input().split()))
    k = int(input())
    a.sort()
    final = []
    temp = []
    recur(-1,len(a),a,temp,k,final)
    print(final)

标签: pythonpython-3.xlistrecursion

解决方案


我最终得到了空列表的列表。

这可能是由于以下声明:

final.append(temp)

您正在将列表附加temp到,finaltemp在发生这种情况后将继续更改,并且final最终将包含一个或多个指向 的最后一个值的指针temp,而不是您附加它时的值。为此,您需要附加一个不会更改的副本:temp

final.append(list(temp))  # make a copy and stash it away

一般来说,我同意@patmcb 关于我们无法猜测这段代码试图做什么的观点。但是,在结构上,我希望一个设计合理的递归函数看起来更像:

def recur(start, end, array, temp, target):
    total = sum(temp)

    if total == target:
        return [list(temp)]  # a list containing a copy of temp

    if total > target or start == end - 1:
        return []

    start += 1
    temp.append(array[start])
    result = recur(start, end, array, temp, target)
    temp.pop()

    return result + recur(start, end, array, temp, target)

for _ in range(int(input())):
    a = sorted(map(int, input().split()))
    k = int(input())

    print(recur(-1, len(a), a, [], k))

输出

> python3 test.py
1
5 10 13 2 4 6
21 
[[2, 4, 5, 10], [2, 6, 13], [5, 6, 10]]
>

推荐阅读