I am attempting to check if a string is a palindrome or not( reads the same forwards and backwards )
I am having trouble understanding why the output is throwing the error that the variable has not been assigned after the code that says it has been assigned. I have a base case and a recursive case.
I also need to use only one return.
def is_palindrome(s)
if len(s)<=1: # if we have reached the end of the string
print("is palindrome")
palindrome = True
print("set palindrome to true")
elif len(s)>1:
print("length not 1, checking again")
if s[0] == s[-1]:
print("leftmost = rightmost")
newstring = s[1:]
newstring = newstring[:-1]
s = newstring
is_palindrome(s)
else:
print("not palindrome")
palindrome = False
return palindrome
Output:
length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
is palindrome
set palindrome to true
Traceback (most recent call last):
line 16, in <module>
print(is_palindrome(s))
line 134, in is_palindrome
is_palindrome(s)
line 134, in is_palindrome
is_palindrome(s)
line 139, in is_palindrome
return palindrome UnboundLocalError: local variable 'palindrome' referenced before assignment
EDIT:
I now have this code however it seems as though it is returning true regardless
CODE:
palindrome = True
#BASE CASE
if len(s)>1:
print("length not 1, checking again")
if s[0] == s[-1]:
print("leftmost = rightmost")
newstring = s[1:]
newstring = newstring[:-1]
s = newstring
is_palindrome(s)
else:
print("not palindrome")
palindrome = False
return palindrome
OUTPUT:
length not 1, checking again
leftmost = rightmost
length not 1, checking again
leftmost = rightmost
length not 1, checking again
not palindrome
True
>Solution :
The issue is that your assuming the palindrome variable is carried throughout the recursion, but it is a different piece of data each time recursion starts. So if you only follow the very first layer:
def is_palindrome(s)
if len(s)<=1: # if we have reached the end of the string
# print("is palindrome")
# palindrome = True
# print("set palindrome to true")
elif len(s)>1:
print("length not 1, checking again")
if s[0] == s[-1]:
print("leftmost = rightmost")
newstring = s[1:]
newstring = newstring[:-1]
s = newstring
is_palindrome(s)
# else:
# print("not palindrome")
# palindrome = False
return palindrome
you get this. I commented out everything that doesn’t run on the first layer, as you can see palindrome is never set. to accomplish what you want, I would take the line
if s[0] == s[-1]:
print("leftmost = rightmost")
newstring = s[1:]
newstring = newstring[:-1]
s = newstring
is_palindrome(s)
and write it like this
if s[0] == s[-1]:
print("leftmost = rightmost")
newstring = s[1:]
newstring = newstring[:-1]
s = newstring
palindrome = is_palindrome(s)