【发布时间】:2021-08-22 17:35:32
【问题描述】:
我正在尝试在 python 中实现 bestSum 算法,我在第 13,14 行有以下脚本。
memo = {}
def bestSum(s, l):
if s == 0:
return []
elif s < 0:
return None
elif s in memo:
return memo[s]
minList = None
for i in l:
temp = bestSum(s-i, l)
if temp != None:
temp = temp + [i] #This works LINE13
# temp.append(i) This does not work LINE14
if minList == None or len(temp) < len(minList):
minList = temp
memo[s] = minList
return minList
我知道“+”运算符返回一个新列表,而 append 函数会改变原始列表。
我的问题是为什么它在我的代码中很重要,因为临时列表仅在接下来的几行中使用。为什么他们给出不同的输出。
【问题讨论】:
-
改变列表意味着你正在修改
memo的内容,而不是准备一个distinct列表添加到memo。 -
谢谢chepner,你的回答有帮助。从来没有,虽然它会改变备忘录中的价值。
-
@ShubhankarSingh 当然可以。如果您将列表添加到 dict,那么您会改变列表,那么列表将被改变并且字典将反映这一点。向容器中添加对象永远不会复制这些对象,至少在 Python 内置函数中不会。
标签: python python-3.x list append dynamic-programming