Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

2 Answers

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.

like image 79
Tim Biegeleisen Avatar answered Jan 20 '26 02:01

Tim Biegeleisen


your function is too long. I prefer to use string[::-1]

#
def is_palindrome(word):

    return word == word[::-1]
like image 29
define is_tofu 1 Avatar answered Jan 20 '26 04:01

define is_tofu 1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!