169k views
4 votes
Write a recursive function "def isPalindrome(string) that returns True if string is a palindrome. A palindrome is a word that is the same frontwards and backwards, eg rotor,

User Maalls
by
4.8k points

1 Answer

3 votes

Edit:

Sorry, I got a little carried away and misread the question! To do this recursively, we need to check to see if the first and last characters in the string are the same. If they are, we slice the first and last characters from the sting and call the function from within itself until there is 0 or 1 characters left (if there is 1 left, we don't have to compare it to anything because it is the center character).

def isPalindrome(string):

if len(string) > 1:

if string[0] == string[-1]:

return isPalindrome(string[1:-1])

else:

return false

return true

--------

Original answer:

To reverse a string in Python, we can use slicing. The syntax is as followed:

string[startingIndex:endingIndex:step]

To reverse the string we can leave the indices blank and set the step to -1. This will slice the string starting at the end, and stepping one character backwards, iterating throughout the string.

def isPalindrome(string):

reversedString = string[::-1]

return string == reversedString

User Randy Newfield
by
4.8k points