Recursion Taco Cat: Why is this not a recursion?

I have written this code

def is_palindrome(word):

  if len(word) == 0 or 1:

    return True

  if word[-1] != word[0]:

    return False

  if word[-1] == word[0]:

    word = word.replace(word[-1], '')

    word = word.replace(word[0], '')

    return is_palindrome(word)

to check whether something is a palindrome and it feels (to me at least) like a recursive code. However, it won’t let me pass and displays this error message:

Define is_palindrome() so that it uses RECURSIVE calls. Do not use iteration!

Could someone explain why my code is not a recursive one? Thanks

This line is an issue. Your function will always immediately return True. Can you see why?

Hint:

What is the boolean value of 1?

2 Likes

Oh, I see why this is an issue. However, if I replace my code with if len(word) == (0 or 1), the code no longer works :frowning:

We have to be a little more explicit when checking multiple conditions. For example:

# your original code was basically interpreted as:
if len(word) == 0 or True:

That condition is always True regardless of the length of word. If you want to also check if length of word is equal to 1, you have to do so very explicitly:

if len(word) == 0 or len(word) == 1:

Considering, however, that the length of word could never possibly be negative, there is a simpler way to see if the length is 1 or less :wink:

1 Like

… I see it now and I feel so dumb hahahaha. Thanks so much for your help, splitting the code helped me pass this obstacle. I didn’t realise python was so picky with its formatting :smiley:

2 Likes

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.