# Recursive function for a palindrome

I’m learning recursive functions with another exercise:

Write a recursive function

def isPalindrome(string) :

that returns True if string is a palindrome, that is, a word that is the same when reversed. Examples of palindromes are “deed” or"rotor". Hint: A word is a palindrome if the first and last letters match and the remainder is also a palindrome.

``````#  Display whether or not a string is a palidrome.
#

def main() :
inputStr = input("Enter a string: ")
if isPalindrome(inputStr) :
print("That's a palindrome.")
else:
print("That isn't a palindrome.")

## Determine whether or not a string is a palindrome.
#  @param string the characters to check
#  @return True if the string is a palindrome, False otherwise
#
def isPalindrome(string) :
if len(string) <= 1 :
return True
if string[0] == string[len(string) - 1] :
return isPalindrome(string[1:len(string) - 1])
else :
return False

# Call the main function.
main()
``````

For the first letter I have string[0]
`if string[0] ==`
and then move inwards to grab the second letter:
`isPalindrome(string[1:`

But for the last letter I have
`== string[len(string) - 1]` : the first time and the second time it looks the same:
`len(string) - 1])`
So where did the first last letter go if the word is rotor, for example. It seems to me that I’m not moving inwards one position from the last one in the case of the last letter.

Thanks a lot!!!

solved!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.