The Python Oracle

python: recursive check to determine whether string is a palindrome

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puddle Jumping Looping

--

Chapters
00:00 Question
01:45 Accepted answer (Score 7)
02:04 Answer 2 (Score 4)
02:32 Answer 3 (Score 3)
02:44 Answer 4 (Score 2)
04:04 Thank you

--

Full question
https://stackoverflow.com/questions/1149...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #recursion

#avk47



ACCEPTED ANSWER

Score 7


In your first example, you forgot a return statement:

def is_palindrome(s):
    if s == '':
        return True
    else:
        if (ord(s[0]) - ord(s[len(s)-1])) == 0:
            # v-- forgot this here
            return is_palindrome(s[1:len(s)-1])
        else:
            return False



ANSWER 2

Score 4


        is_palindrome(s[1:len(s)-1])

needs to be...

        return is_palindrome(s[1:len(s)-1])

in your first version, or

        result = is_palindrome(s[1:len(s)-1])

in your second. Otherwise, you never actually propagate the recursive call's return value back to the original caller.




ANSWER 3

Score 2


def is_palindrome(s):
    if not s:
        return True
    else:
        return s[0]==s[-1] and is_palindrome(s[1:-1])

or, if you want a one-liner:

def is_palindrome(s):
    return (not s) or (s[0]==s[-1] and is_palindrome(s[1:-1]))

Hope that helps




ANSWER 4

Score 2


Let's step through your second example, line by line.:

def is_palindrome(s):

In this case let's let s = "abba", which is the first string you got an error on:

        if s == '':

is evaluated as

        if 'abba' == '':

Which is False, so we skip ahead to else:

        else:
            if (ord(s[0]) - ord(s[len(s)-1])) == 0:

This if statement is equivalent to:

            if (97 - 97) == 0:

It's True, so recursion happens:

                is_palindrome(s[1:len(s)-1])

or

                is_palindrome('bb')

Now whatever is the result of this recursion, we ignore it, because the return value is not saved. Thus, when we get to this line:

        return result

We never defined what result was, so Python flips out.

Other posters already did an excellent job of answering your question. I'm posting to demonstrate the importance of tracing a program to find/fix bugs.