I'm not understanding why snippet 1 works while the 2nd one doesn't. The 2nd code returns local variable 'ans' referenced before assignment error. Even when I do change 2 to include print(ans) right after def dfs(node): (basically the same structure as 1), it returns the same error. Would appreciate your answer as to why this is happening!
Snippet 1:
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Snippet 2:
from collections import defaultdict
#class Solution:
def minReorder( n, connections):
seen = set()
ans = 0 # to count # of changes
# graph preprocessing
cities = defaultdict(list)
for i in connections:
a, b = i
cities[a].append(b)
# dfs
def dfs(node):
#print(ans) This is the same structure as snippet 1 but also gives the same error
#nonlocal ans This fixes the issue!
for n in cities[node]:
if n not in seen:
seen.add(n)
ans += 1
dfs(n)
for i in range(n):
if i not in seen:
seen.add(i)
dfs(i)
print(f'outside {ans}')
return ans
Test case for snippet 2 if needed:
minReorder(6, [[0,1],[1,3],[2,3],[4,0],[4,5]])
I fixed the error by using nonlocal ans but not sure why it's required for 2 and not for 1