【发布时间】:2020-07-22 19:21:22
【问题描述】:
class Trie:
def __init__(self):
self.children = [None] * 26
self.count = 0
def solve(words,k):
fap=0
trie = Trie()
for x in words:
cur = trie
for ch in x:
i = ord(ch) - ord('A')
if(cur.children[i] is None):
cur.children[i] = Trie()
cur = cur.children[i]
cur.count+=1
def dfs(node,depth=0):
for c in range (0,26):
if(node.children[c] is not None):
dfs(node.children[c],depth+1)
node.count+=node.children[c].count
while(node.count>=k):
fap+=depth
node.count-=k
dfs(trie)
return fap
words 初始化为['foo','bar']
k 初始化为 2
线
fap+= depth
给出错误:
local variable 'fap' referenced before assignment
即使fap 在solve 函数的第一行被赋值为0。
【问题讨论】:
-
但是DFS函数在solve函数里面
-
@Ronald 缩进是正确的,
dfs是在solve里面定义的,在solve的末尾调用。 -
我的错误。我删除了它并能够重现错误。
-
如果我将 fap 变量声明为数组而不是 fap 变量,则不会产生此错误.. 为什么会这样?