0

I am leetcoding, when doing recursion, I used to define an internal function which does the recursion job and some variables in the outer function. like this:

def recur(root):
  res = []
  
  def bt(node):
    # specific recursive job in this function
    # and modify outer res
    
  bt(root)
  return res

This writing style always works but today when I want to define a variable out the inside function like this:

class Solution:
    @staticmethod
    def is_balanced(root):
        fla = True

        def post_tr_verify(node):
            if not node or not fla:
                return 0
            left = post_tr_verify(node.left)
            right = post_tr_verify(node.right)
            if abs(left - right) > 1:
                fla = False
                return 0
            return max(left, right) + 1

        post_tr_verify(root)
        return fla

it reminds me 'UnboundLocalError: local variable 'fla' referenced before assignment', I fixed it by add one sentence inside the post_tr_verify function: nonlocal fla. But I still can't figure out why my writing style doesn't work this time. Why this error comes?

My previous writing recursion example:

class Solution:
    @staticmethod
    def permute(nums):
        cur, res = [], []
        print(id(res))

        def bt(li):
            if li and len(li) == len(nums):
                res.append(cur[:])
                print(id(res))
                return
            for ele in nums:
                if not li:
                    cur.append(ele)
                    bt(cur)
                    cur.pop()
                elif ele not in li:
                    cur.append(ele)
                    bt(cur)
                    cur.pop()

        bt(cur)
        return res

if __name__ == '__main__':
    so = Solution()
    print(so.permute([1, 2, 3]))

The running result of this snippet shows the res has been successfully referenced since they shown the same id value. Why the fla one doesn't work?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
ccc
  • 11
  • 2
  • @Tomerikoo, Thanks for your reply! I got the keypoint from that post that 'If a variable is assigned within a function, it is treated by default as a local variable.' Does that means Python saw the assignment operation in my second code block : 'fla = False' and implicitly regards it as a local variable therefore result fail in examine 'if not fla'? If so can I infer the append operation doesn't belongs to 'assignment operation' cause it modify the variable in place? – ccc Mar 14 '21 at 11:12
  • No, the fact that `.append` works in-place on a list is irrelevant. `x = whatever` is an *assignment* to the variable `x`. `x.append(whatever)` merely *accesses* `x`, then calls a method on the result. – juanpa.arrivillaga Mar 14 '21 at 11:37

0 Answers0