分配前引用的局部变量,即使已分配

时间:2020-07-22 19:21:22

标签: python variables scope

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。

2 个答案:

答案 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(),因为否则您将无法在内部函数中访问变量

相关问题