Python默认使用字符串键时的奇怪行为



很抱歉,如果这个问题之前已经回答过了,但是很难用一句话解释这种情况,所以我的搜索没有产生任何好的结果。

我试图解决LeetCode 1048。你可以在下面看到我的解决方案。我觉得我的解决方案合乎逻辑。然而,当我运行它时,结果总是短。

因此,我试着在循环中间做print(dp[newWord])来调试它,然后它神奇地工作了。事实上,你甚至不需要打印它,只要在代码中输入它就可以使它工作。

谁能给我解释一下为什么defaultdict有这个行为?我已经广泛使用它,我不记得以前有过这个问题。

import collections
def longestStrChain(words):
words.sort(key=lambda word: (len(word), word))
dp = collections.defaultdict(int)
result = 1

for word in words:
if len(word) == 1:
dp[word] = 1
else:
for i in range(len(word)):
newWord = str(word[:i] + word[i+1:])
# dp[newWord] # uncomment this line and it will work
if newWord in dp:
dp[word] = max(dp[word], dp[newWord] + 1)
result = max(result, dp[word])
else:
dp[word] = 1

return result
print(longestStrChain(["a","b","ba","bca","bda","bdca"]))
# expecting 4, but always getting 3 until I uncomment the line

一旦你做了dp[newWord],newWord in dp就是True。参见文档:

__missing__(key)

如果default_factory不是None,则不带参数调用它,为给定的提供默认值,该值被插入到的字典中。,并返回。

(粗体)

最新更新