我正在实现DFS算法,我想创建一个字典列表。但我发现,如果我使用[dict()] * n
,我会得到意想不到的结果。
我不确定“[dict()] * n
”和“for
循环与.append(dict())
”之间有什么区别。
任何提示都表示赞赏。
def DFS1(nums, level, target, dp):
if level == len(nums):
if target == 0:
return 1
else:
return 0
if target in dp[level]:
return dp[level][target]
cnt1 = DFS1(nums, level + 1, target + nums[level], dp)
cnt2 = DFS1(nums, level + 1, target - nums[level], dp)
dp[level][target] = cnt1 + cnt2
return cnt1 + cnt2
测试代码是:
nums = [1,1,1,1,1]
n = len(nums)
target = -3
#dp = [dict()] * n #<== This does not work as expected
dp = []
for i in range(0, n):
dp.append(dict())
resCnt = DFS1(nums, 0, target, dp)
print(resCnt)
答案 0 :(得分:2)
基本上发生的是你正在创建引用:
x = [dict()] * 10
print x
>[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}] #looks fine
x[0]['x'] = 3 #all references share same memory
print x
[{'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}, {'x': 3}]
视觉跟随发生:
为了避免referencing
,你必须明确告诉python每次都创建新的词典:
x = [{} for x in range(10)]
print x
>[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
x[0]['x'] = 3
print x
>[{'x': 3}, {}, {}, {}, {}, {}, {}, {}, {}, {}]
视觉表示:每个存储桶都有dict的自己的副本: