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。
答案 0 :(得分:1)
此行
fap+=depth
位于dfs
函数内部,而不是solve
。
在fap
内分配给dfs
时,默认情况下它将被视为dfs
的本地对象,因此会出错。
如果要从封闭的范围fap
函数中更新solve
变量,则必须将其声明为nonlocal
:
def dfs(node,depth=0):
nonlocal fap
for c in range (0,26):
...
答案 1 :(得分:0)
您需要在nonlocal fap
函数中添加dfs()
,因为否则您将无法在内部函数中访问变量