0

I was working on LeetCode problem Longest Palindromic Substring and had the following code:

    def longestPalindrome(s):
    """
    :type s: str
    :rtype: str
    """
    length = len(s)
    lookup = [[False for i in range(1000)] for j in range(1000)]
    for i in range(0,length):
        lookup[i][i] = True
        longestBegin = i
        maxL = 1
    for i in range(0,length-1):
        if s[i] == s[i+1]:
            lookup[i][i+1] = True
            longestBegin = i
            maxL = 2
    for len in range(3,n+1):
        i = 0
        while i <= n-len+1:
            j = i + len -1
            if lookup[i+1][j-1] and s[i] == s[j]:
                lookup[i][j] = True
                longestBegin = i
                maxL = len
    return s[longestBegin:longestBegin+maxL]

When i call the function:longestPalindrome('abdad'), I got error:

"Runtime Error Message: Line 7: UnboundLocalError: local variable 'len' referenced before assignment".

Any help would be appreciated.

Shawn TIAN
  • 417
  • 4
  • 10
  • 2
    _Don't use `len` as a variable name._ – Aran-Fey Oct 03 '17 at 09:14
  • @Rawing: it's fine in a function provided you have no intention to use the built-in; using `len` as a local, *by itself* is not the cause of the error. – Martijn Pieters Oct 03 '17 at 09:16
  • @MartijnPieters You're right, it's not the cause of the error - but it's generally a good idea to avoid shadowing builtins. I suppose I could/should have elaborated a little bit on that. – Aran-Fey Oct 03 '17 at 09:23

1 Answers1

0

You are using len as a local variable name, by assigning to it with a for loop:

for len in range(3,n+1):

This makes len a local in the whole function, masking the built-in len() function. You can't use the name len both as a local and a global.

As a result, using length = len(s) fails because the local name len hasn't had anything assigned to it yet (it is not yet bound). Use a different name for the for loop target.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343