python - 从递归中取出列表
问题描述
基本情况下的临时是我需要的答案。它应该被附加到最后。但我最终得到了空列表的列表。有什么建议吗?
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)
解决方案
我最终得到了空列表的列表。
这可能是由于以下声明:
final.append(temp)
您正在将列表附加temp
到,final
但temp
在发生这种情况后将继续更改,并且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]]
>
推荐阅读
- php - 如何修复 Visual Studio Code 中的“错误:生成 php ENOENT”?
- amazon-web-services - EB CLI 在应用程序根目录中找不到 Dockerfile 或 Dockerrun.aws.json 文件
- core-data - performFetch 创建具有太多数据的可区分数据源快照
- function - Pyspark - 在两个字符串列上合并导致错误 - 无法转换为结构
- vue.js - 通过槽向子组件添加多个组件
- rust - 如果我在调用 present 之前更改画布的 vew_port,为什么会有旧图像闪烁?
- node.js - ReferenceError: _id 未定义
- android - RecyclerView 包装了它的内容
- javascript - 如何在 Microsoft Playwright 中创建自动化 API 测试?
- c++ - 如何在 C++ 中使用类和对象重载 << 运算符