Search code examples
pythonrecursionpalindrome

Checking for palindrome using recursion in PYTHON


I am checking if a word is a palindrome, and I cant seem to get my code to respond. I feel like its pretty sound, but apparently I'm missing something. can someone point out what that may be?

def reverse(usrWrd, index):   
    newWord = ""  

    if index == len(usrWrd):
        return newWord
    else:
      newWord += usrWrd[index]
      return reverse(usrWrd, index + 1)

def main(): 
    usrWrd = input("please enter a word to check for palindrome-ness:")

    result = reverse(usrWrd, 0)
    if result == usrWrd:
        print("That word is a palindrome")
    else:
        print("Sorry,",usrWrd,  "is NOT a palindrome")

main()

Solution

  • # Correct approach to your solution
    def reverse(usrWrd, index, newWord):
        if index < 0:
            return newWord
        else:
          newWord += usrWrd[index]
          return reverse(usrWrd, index - 1, newWord)
    
    def main():
        newWord = ""
        usrWrd = input("please enter a word to check for palindrome-ness:")
        result = reverse(usrWrd, len(usrWrd) - 1, newWord)
    
        if result == usrWrd:
            print("That word is a palindrome")
        else:
            print("Sorry,",usrWrd,  "is NOT a palindrome")
    
    #############################################################
    # Alternate approach
    def isPalindrome(usrWord):
        sLen = len(usrWord)
        if sLen <= 1:
            return True
        else:
            if usrWord[0] != usrWord[sLen-1]:
                return False
            else:
                return isPalindrome(usrWord[1:sLen-1])
    
    def main():
        newWord = ""
        usrWrd = input("please enter a word to check for palindrome-ness:")
        result = isPalindrome(usrWrd)
    
        if result:
            print("That word is a palindrome")
        else:
            print("Sorry,",usrWrd,  "is NOT a palindrome")
    
    #############################################################
    # Pythonic way as suggested by 'Yaman Jain'
    if usrWord == usrWord[::-1]:
        return True # Palindrome
    else:
        return False # Not Palindrome