Search code examples
pythonstringrecursionpalindrome

Recursion Function Isn't Working


Okay, so I'm trying to make a recursive function that returns True if the function is a palindrome, and False otherwise. However, it doesn't go to the very end, and randomly stops.

Code:


def is_palindrome(word):

    if len(word) == 1 or len(word) == 0:
        return True
    else:
        lst = len(word) - 1
        if word[0] == word[lst]:
            print(len(word), " --> ", word)
            print(word[0], " # ", word[lst])
            is_palindrome(word[0+1:lst])
        else: 
            return False

For the life of me, I can't figure out why. Here's a sample output:

7  -->  racecar
r  #  r
5  -->  aceca
a  #  a
3  -->  cec
c  #  c

^ It stops right here. Why doesn't it continue and return True when length = 1?

Solution

  • You need to return your call to the recursive function:

    def is_palindrome(word):
    
        if len(word) == 1 or len(word) == 0:
            return True
        else:
            lst = len(word) - 1
            if word[0] == word[lst]:
                print(len(word), " --> ", word)
                print(word[0], " # ", word[lst])
                return is_palindrome(word[0+1:lst])     # change here
            else: 
                return False
    

    The reason you code appears to stop at the final step of recursion is because you never actually return a value in that case. In some programming languages, such as C or maybe Java, such code would not even compile. Python appears to tolerate it, though it results in your current behavior.