1

From what I read here, child scope should have access to variables defined in the parent scope. However, in my case, I get an unresolved error on count. Any reason why this happened?

def find_kth_largest_bst(root, k):
        count = 0
    def _find_kth_largest_bst(root, k):
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1 #unresolved error here??
        pass
jen007
  • 1,389
  • 3
  • 15
  • 19

2 Answers2

2

You can use nonlocal keyword to access variables from parent scope.

def find_kth_largest_bst(root, k):
    count = 0
    def _find_kth_largest_bst(root, k):
        nonlocal count  # This will access count from parent scope
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1
        pass
D Dhaliwal
  • 552
  • 5
  • 23
0

what you are doing is using Inner Functions, which is different from class inheritance. Another quastion very similar is this one:

Python nested functions variable scoping

from this question one answer says:

" The documentation about Scopes and Namespaces says this:

A special quirk of Python is that – if no global statement is in effect – assignments to names always go into the innermost scope. Assignments do not copy data — they just bind names to objects.

it means that you may solve your error with global or nonlocal statement

def find_kth_largest_bst(root, k):
    global count
    count = 0
    def _find_kth_largest_bst(root, k):
        if not root:
            return None

        _find_kth_largest_bst(root.right, k)
        count += 1 #unresolved error here??
        pass

Another thing here is that count = 0 have double tab, or 8 spaces, while it should have only one.

Community
  • 1
  • 1
Guinther Kovalski
  • 1,629
  • 1
  • 7
  • 15