3

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?
kiyah
  • 1,502
  • 2
  • 18
  • 27

2 Answers2

6

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • That makes so such sense. Thank you very much. I'll be more careful with my recursive statements now. Thank you!!! –  Feb 05 '18 at 05:01
1

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

#
def is_palindrome(word):

    return word == word[::-1]
  • Haha, I'm aware of that. But I don't quite understand it, so I'm gonna avoid it. But thank you! –  Feb 05 '18 at 05:00