0

I need to define a recursive function to check if a string is a palindrome.

Below's my code:

def palindrome_recur(string):

    if len(string)==0 or 1:
        return True
    else:
        if string[0] == string[-1]:
            return palindrome_recur(string[1:-2])
        else:
            return False

It passes a few test cases, but doesn't work for the string "chipmunks". Can anybody tell me what I might have overlooked?

anon582847382
  • 19,907
  • 5
  • 54
  • 57
user3531425
  • 25
  • 2
  • 5

2 Answers2

1

You should pass the recursive call as: return palindrome_recur(string[1:-1]) instead.

Also, your len check is not correct. Do this instead:

if len(strg)==0 or len(strg)==1:
sshashank124
  • 31,495
  • 9
  • 67
  • 76
1

The problem is this:

if len(string)==0 or 1:

That checks whether either of len(string) == 0, or 1 is true. Since 1 is always true, the whole expression is always true and your function always returns True.

You should use

if len(string) <= 1:

instead.

Then, you'll find out about the problem with indexing to -2 that the other answers mention.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79