Skip to content Skip to sidebar Skip to footer

Python: Recursive Check To Determine Whether String Is A Palindrome

My task is to define a procedure is_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single letter sho

Solution 1:

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

Solution 2:

        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.


Solution 3:

# ask user to enter any string
a = raw_input("Enter the string : ")
#palindrome check
print (a == a[::-1]) and "String is palindrome" or "String is not palindrome"

Solution 4:

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.


Solution 5:

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


Post a Comment for "Python: Recursive Check To Determine Whether String Is A Palindrome"