The Python Oracle

python: recursive check to determine whether string is a palindrome

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Python: Recursive Check To Determine Whether String Is A Palindrome
01:23 Accepted Answer Score 7
01:43 Answer 2 Score 4
02:11 Answer 3 Score 3
02:23 Answer 4 Score 2
02:42 Answer 5 Score 2
03:52 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.