Utkarsh
Utkarsh

Reputation: 60

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 is initialized to ['foo','bar'] k is initialized to 2

The line

fap+= depth

gives the error:

local variable 'fap' referenced before assignment

even though fap is assigned to 0 in first line of the solve function.

Upvotes: 1

Views: 1082

Answers (2)

Pierre-Loic
Pierre-Loic

Reputation: 1554

You need to add nonlocal fap in your dfs() function because otherwise you can't access your variable in your inner function

Upvotes: 0

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

This line

fap+=depth

is inside the dfs function, not solve.

As you assign to fap inside dfs, it will by default be considered local to dfs, hence the error.

If you want to update the fap variable from the enclosing scope, the solve function, you must declare it nonlocal:

   def dfs(node,depth=0):
        nonlocal fap
        for c in range (0,26):
        ...
 

Upvotes: 1

Related Questions