0

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 :)

  • A small part of your question that isn't addressed by the answers in the duplicate is why `nums[:]=snap` works even without `global`. The answer is that `nums[:]=snap` isn't an assignment to the `nums` *variable* - it doesn't *assign a new value* to `nums`; it simply *mutates* the list stored in `nums`. – Aran-Fey Apr 20 '22 at 08:54
  • Oh, and if you get `name 'nums' is used prior to global declaration`, then just move the `global nums` to the top of your function... – Aran-Fey Apr 20 '22 at 08:57
  • @Aran-Fey Thanks a lot. Moving `global nums` to the top works:) – EricForFang Apr 20 '22 at 15:47

0 Answers0