0

I am trying to write my first recursive function in Python. It is supposed to take a word as input and then check whether that word is a palindrome or not.

Here is my code:

def checkPalindrome(str):

    if len(str) == 1:
        return True

    elif str[0] == str[len(str)-1]:
        newstr = str.replace(str[0], "")
        newstr = str.replace(str[len(str)-1], "")
        checkPalindrome(newstr)

def main():
    word = raw_input("Give a name: ")

    if checkPalindrome(word):
        print '%s is a palindrome' % word
    else:
        print '%s is NOT a palindrome' % word

if __name__ == '__main__':
    main()

The problem I am having is that the function checkPalindrome() only works for 1 letter palindromes. It only returns True with something like "k". It also correctly returns false for non palindromes.

But here is the problem: if I give my program a palindrome like wowow, it should return True by calling itself until the string is only 1 character long, in which case it should return true by checking the string is of length 1. But when my program gets to return True after the recursion and after the string has only one character left it returns False!

I even checked that the line of code "return True" is actually ran (through the debugger), and it is being run. But I end up with the else-statement in my main function even if I enter a palindrome.

Can someone with experience in recursion tell me why my function seems to return False even though the line "return True" is being called when I enter a palindrome?

user5846939
  • 415
  • 4
  • 11
  • 1
    Why do it this way when you can simply compare the original string to a reversed copy? – Chris_Rands Oct 12 '16 at 14:58
  • 1
    If the first and last character match, you do not return anything. – wwii Oct 12 '16 at 14:58
  • You shouldn't use `str` as parameter name, since you're hiding the `str` type. Call it `word` for example. Plus, you can replace the whole content of you function by `return word == word[::-1]`. – S. de Melo Oct 12 '16 at 15:01
  • 2
    Even if you need to write a recursive function as an exercise, your `.replace` are dangerous. All characters identical to the first/last one will be replaced! Just do `return checkPalindrome(word[1:-1])`. By the way `word[len(str)-1]` is better written `word[-1]`. – S. de Melo Oct 12 '16 at 15:05

0 Answers0