gpt4 book ai didi

python - arr.append(curr) 和 arr.append(curr[ :])

转载 作者:行者123 更新时间:2023-12-04 00:17:33 24 4
gpt4 key购买 nike

产生幂集的函数给出了正确的输入。然而,用 append(curr) 替换 append(curr[:]) 会给出一个空列表的列表。是什么原因?

def subsets(nums):
def backtrack(first = 0, curr = []):
# if the combination is done
if len(curr) == k:
output.append(curr)
return
for i in range(first, n):
# add nums[i] into the current combination
curr.append(nums[i])
# use next integers to complete the combination
backtrack(i + 1, curr)
# backtrack
curr.pop()

output = []
n = len(nums)
for k in range(n + 1):
backtrack()
return output

最佳答案

正如其他答案所指出的,cur[:] 复制了 cur。如果不制作副本,output 最终会包含同一列表的许多副本 - 每次调用 cur.appendcur.pop< 时,每个列表都会被修改.

列表最终为空,因为每次调用 cur.append 都会调用一次 cur.pop,这确保了cur 的“最终”迭代将是空的。

关于python - arr.append(curr) 和 arr.append(curr[ :]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62806820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com