I define a variable in a function, and I want to use this variable in inner function defined in the outer function. However, there is an error: this variable referenced before assignment. I don't know why.
class Solution(object):
def findItinerary(self, tickets):
"""
:type tickets: List[List[str]]
:rtype: List[str]
"""
length = len(tickets)
visit = [1 for i in range(length)]
tmp = []
result = []
def dfs(tickets, ticket):
if len(tmp) == length:
tmp.append(ticket[1])
if len(result) == 0 or (result != [] and result[1:] > tmp[1:]):
result = tmp
tmp.pop()
return
for i in range(length):
if visit[i] == 1 and ticket[1] == tickets[i][0]:
tmp.append(ticket[1])
visit[i] = 0
dfs(tickets, tickets[i])
visit[i] = 1
tmp.pop()
for count in range(length):
if tickets[count][0] == "JFK":
visit[count] = 0
tmp.append(tickets[count][0])
dfs(tickets, tickets[count])
tmp.pop()
visit[count] = 1
return result
"result" is the variable. And error is like this:
UnboundLocalError: local variable 'result' referenced before assignment
if I replace
result = tmp
with
del result[:]
result.extend(tmp)
Then it works. And I am so confused about this.