赋值前引用的局部变量,即使它已赋值
Local Variable referenced before assignment even though it is assigned
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。
这一行
fap+=depth
在 dfs
函数内,而不是 solve
。
当您在 dfs
内分配给 fap
时,默认情况下它将被视为 dfs
的本地,因此出现错误。
如果您想从封闭范围更新 fap
变量,即 solve
函数,您必须声明它 nonlocal
:
def dfs(node,depth=0):
nonlocal fap
for c in range (0,26):
...
您需要在 dfs()
函数中添加 nonlocal fap
,否则您无法在内部函数中访问您的变量
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。
这一行
fap+=depth
在 dfs
函数内,而不是 solve
。
当您在 dfs
内分配给 fap
时,默认情况下它将被视为 dfs
的本地,因此出现错误。
如果您想从封闭范围更新 fap
变量,即 solve
函数,您必须声明它 nonlocal
:
def dfs(node,depth=0):
nonlocal fap
for c in range (0,26):
...
您需要在 dfs()
函数中添加 nonlocal fap
,否则您无法在内部函数中访问您的变量