Reputation: 13
so i have this code and the goal is to see if an word is an palindrome and is supposed to return true if the word is an palindrome and false if it isn't. for now it always returns false.
here is my code so far:
# main.py
def pal(string):
if len(string)==1 or len(string)==0:
return True
if string[1] == string[len(string)-1]:
pal(string[1,-1])
else:
return False
print(pal("dad"))
please tell me how to fix it and not try to shorten it because I want to learn from my mistakes.
Upvotes: 1
Views: 1196
Reputation: 24691
First of all, your check for "first character equals last character" should be
if string[0] == string[-1]:
Strings/lists/etc. are 0-indexed, meaning that the first element has index 0. In python, you can access the last element of a string/list by using the index -1
(or the second last with -2
, etc.), which counts backwards from the back of the array. Other languages do require you to take the length of the string/list and subtract one, but in python string[len(string) - 1]
and string[-1]
are functionally identical.
Next, the syntax for "slicing" a string or list is :
, not ,
:
pal(string[1:-1])
And finally, you need to return this recursive call. Just calling the function without explicitly returning it won't do anything:
return pal(string[1:-1])
Upvotes: 4