0

I have declared a dictionary globally and a variable as well. Now, when accessing both in a class, I can access the dictionary but for accessing the other variable, I get the UnboundLocalError. For solving this, I used the line of code: global curr_length and then access it and it ran. But I wanted to known why is this additional line of code required for a normal integer variable whereas not required for a dictionary?

The code is:

memoized = {}
curr_length = 0
curr_pal = ""


class Solution:
    def check_palindrome(self, str_):
        if len(str_) <= 1:
            return False
        global curr_length
        if len(str_) <= curr_length:
            return False
        if memoized.get(str_, None):
            return memoized[str_]
        if str_ == str_[::-1]:
            memoized[str_] = True
            curr_length = len(str_)
            return True
        memoized[str_] = False
        return False

    def longest_palindrome(self, str_, starting_index):
        if len(str_) <= 1:
            return None
        n = len(str_)
        if self.check_palindrome(str_[starting_index:n]):
            return str_
        n -= 1
        self.longest_palindrome(str_[starting_index:n], starting_index)

    def longestPalindrome(self, s: str) -> str:
        for starting_index in range(len(s)):
            pal = self.longest_palindrome(s, starting_index)
            if pal:
                return pal
        return ""


solution = Solution()
print(solution.longestPalindrome("babad"))
Aviral Srivastava
  • 4,058
  • 8
  • 29
  • 81

1 Answers1

2

Short:

You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.

As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to: Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?

EXPLANATION:

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

Let's see an example on how a global variable is created in Python.

x = "global"

def foo():
    print("x inside :", x)

foo()
print("x outside:", x)

When we run the code, the will output be:

x inside : global
x outside: global

In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

What if you want to change value of x inside a function?

def foo():
    x = x * 2
    print(x)
foo()

When we run the code, the will output be:

UnboundLocalError: local variable 'x' referenced before assignment

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

To make this work we use global keyword

Community
  • 1
  • 1
pissall
  • 7,109
  • 2
  • 25
  • 45
  • You need to add more explanation of how to use `global`. AFAICT, the OP is doing what your link suggests with the `curr_length` variable – Paul H Sep 22 '19 at 16:52
  • The answer is trying to explain that he is trying to change the value of `curr_length` with `curr_length = len(str_)` – pissall Sep 22 '19 at 16:53
  • So how does that relate to their dictionary? – Paul H Sep 22 '19 at 16:55
  • and he OP used the `global` keyword with `curr_length`, as your link suggests – Paul H Sep 22 '19 at 16:57