Reputation: 5
While trying to solve a problem on leetcode, I ran into an error "local variable referenced before assignment". Below I have given the entire code (the logic of the code itself is not my question). I have defined the variable within the outer function. I read somewhere, that in python, the scope of a variable works in this way - the variable is first searched locally, then in outer functions (if there are any), then global. In my code, no local variable "total" exists, but there is one defined in the outer function. Is my understanding of scope of variables wrong? Also, I used something similar in another problem but instead of an integer, I was using a list, which was similarly defined in the outer function only, and being appended in the inner function. In this case, no such error occurred. What I am doing wrong here? Any clarification is greatly appreciated.
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
total = 0
if root is None:
return 0
def helper(root, sum, rem):
if root is None:
return
if root.val == rem:
total += 1
if root.left is not None:
helper(root.left, sum, sum - root.val)
if root.right is not None:
helper(root.right, sum, sum - root.val)
return
helper(root, sum, sum)
return total
'''
Upvotes: 0
Views: 121
Reputation: 2331
To fix this, use a nonlocal
declaration:
class Solution:
def pathSum(self, root: TreeNode, sum: int) -> int:
total = 0
if root is None:
return 0
def helper(root, sum, rem):
nonlocal total
if root is None:
return
if root.val == rem:
total += 1
if root.left is not None:
helper(root.left, sum, sum - root.val)
if root.right is not None:
helper(root.right, sum, sum - root.val)
return
helper(root, sum, sum)
return total
Essentially, total += 1
implicitly tells Python that total
is a local variable.
Have a look at this answer
Upvotes: 1