Leetocode keeps giving me this UnboundLocalError, and I don't know why...
This is my code
class Solution:
def longestPalindrome(self, s: str) -> str:
def isPalindrome(s):
if len(s) == 1:
return True
if len(s) == 2 and s[0] == s[1]:
return True
else:
if s[0] == s[-1]:
return isPalindrome(s[1:-1])
else:
return False
max_ = 0
lenght = len(s)
for i in range(lenght):
for r in range(i + 1, lenght):
if isPalindrome(s[i:r]):
len_ = r - i + 1
if len_ > max_:
max_ = len_
final = s[i:r]
return final
and the error it gives me is
UnboundLocalError: local variable 'final' referenced before assignment
return final
Can someone please help me understand why this may be occurring?
I think the problem may be given in the case where the final string is of len() = 1. In that case it might be a problem the s[i : r]
your
final
variable is defined inside theif
block and is not visible outside. just declare it outside to get rid of this erro