I'm dealing with a question from LeetCode #47. The code works just fine but I've got an error I can't figure out why.
In short, snap
is used to record variable nums
in every backtrack
, so that nums
can be recovered at the end of the function. But once Line 9 is executed, here comes a 'nums' referenced before assignment'
error. However, if I change Line 16 to nums[:]=snap
, the error is gone.
I know maybe global variable can only be referred rather than assigned without the global
declaration. But it's still wield because the debugger didn't even execute nums=snap
in Line 16. How did it know it's a local variable? And if I global nums
, here comes another error called name 'nums' is used prior to global declaration
.
nums=[1,2,2]
nums.sort()
m=len(nums)
Out=[]
def backtrack(i,snap):
if i==m :
Out.append(nums[:])
else:
snap=nums[:] #Line 9
for j in range(i,m):
if i!=j and nums[j]==nums[i]:
continue
else:
nums[i],nums[j]=nums[j],nums[i]
backtrack(i+1,nums[:])
nums=snap #Line 16
backtrack(0,nums[:])
print(Out)
Any help would be very appreciated as I'm new in the world of Python :)