python 3.xx Recursion A palindrome is a word or phrase that reads the same forwa
ID: 3823447 • Letter: P
Question
python 3.xx
Recursion
A palindrome is a word or phrase that reads the same forwards or backwards (e.g. "dad", "mom", "deed").
Write a recrusive function, isPalindrome that accepts a string and returns whether the string is a palindrome. A string is a palindrome if:
*it is an empty string or consists of a single letter, or
*if the first and last characters are the same, and the rest of the string forms a palindrome
Your function should ignore spaces and only compare letters.
'
this is what I have , works with different words or phrases like "racecar", "!", but not with "never odd or even"
def isPalindrome(string):
if len(string) <= 1:
return True
elif string[0] != string[len(string) - 1]:
return False
return isPalindrome(string[1:len(string) - 1])
Explanation / Answer
The code finds palindrome or not. But there is an additional check which needs to be done as per the question statement "Your function should ignore spaces and only compare letters."
The below code written by me will execute properly to check palindrome along with the additional check for spaces in between them and ignore them.
def isPalindrome(string):
if len(string) <= 1:
return True
if string[0] == ' ':
string = string[1:len(string)];
if string[len(string) - 1] == ' ':
string = string[0:len(string) - 1];
if string[0] != string[len(string) - 1]:
return False
return isPalindrome(string[1:len(string) - 1])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.