Reputation: 9
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]
Upvotes: -1
Views: 54
Reputation: 2006
Testcase in which s
consist of only one letter. like ("a","d") your inner for loop is not executing and hence you define final inside the if is not initialize and you are returning final
hence unbound error occurs.
for ex. let's say s="s" Dry run-:
max_ :0
lenght :1 (i.e len(s))
for i in range(1):
for j in range(1,1) (i.e when first loop iterating i=0) no inner loop run
Exit()
return Final #Unbound error
To solve this error you can initialize final
outside. or you can add a condition if len(s)==1: return 1
also your code solution has time complexity O(n^2) I think it will show Time limit exceeded.
Upvotes: 0
Reputation: 6904
your final
variable is defined inside the if
block and is not visible outside. just declare it outside to get rid of this erro
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)
final = 0 # declared final here
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
Upvotes: 0