Vincent
Vincent

Reputation: 329

What is wrong with this Palindrome function?

UPDATE: Thanks to the answers below, I now know that it is an error in the function and has nothing to do with Python's behavior. (My foul) I've since changed the title from "Could Python skip spaces when iterating through a string?" to "What is Wrong with this Function?" so future readers will know that the answers they'll find here pertain to the function, not to Python.

I made a function in Python that determines whether a string is a Palindrome or not. Basically, it iterates from the left and right simultaneously, and checks if any characters are not equal. If so, it returns False. After it reaches the middle, it stops iterating and returns True.

def isPalindrome(string):
    l = 0
    r = -1
    while(l < r+2):
        if string[l] != string[r]:
            return False
        l += 1
        r -= 1

    return True

palin = raw_input("Enter string: ")
if(isPalindrome(palin)):
    print "\""+palin+"\"","is a Palindrome."
else:
    print "\""+palin+"\"","isn't a Palindrome."

It works, but for some reason it also identifies strings like 'pythonnoh ty p' as a Palindrome. Although sometimes this may be a good thing, I'm wondering why the function appears to skip the spaces in the string. It should return False since ' ' does not equal 'y', but it doesn't.

Is there a problem in my code or is it a behavior of Python?

Upvotes: 0

Views: 172

Answers (2)

Vikram Saran
Vikram Saran

Reputation: 1143

It seems like you have a problem with your while loop.

I added a quick debug statement, and ran some tests for you that should reveal the problem.

>>> def isPalindrome(string):
    l = 0
    r = -1
    while(l < r+2):
        if string[l] != string[r]:
            return False
        print "left: %s" %string[l]
        print "right: %s" %string[r]
        l += 1
        r -= 1

    return True

>>> isPalindrome("ono")
left: o
right: o
True
>>> isPalindrome("on o")
left: o
right: o
True
>>> isPalindrome("palindrome")
False
>>> isPalindrome("palinilap")
left: p
right: p
True
>>> isPalindrome("palinalap")
left: p
right: p
True

Upvotes: 3

Hyperboreus
Hyperboreus

Reputation: 32449

After comparing string[0] with string[-1] the values for l and r are 1 and -2. As 1 < 0 is not true, your while loop ends.

Try this:

def isPalindrome(s): return s == s[::-1]

If you want to ignore whitespaces, you can extend it a bit:

def isPalindrome(s, ignoreSpaces = False):
        if ignoreSpaces:
                s = s.replace(' ', '')
        return s == s[::-1]

print (isPalindrome ('pythonnohtyp') )
print (isPalindrome ('pythonnohtyp', True) )
print (isPalindrome ('pythonnoh ty p') )
print (isPalindrome ('pythonnoh ty p', True) )

Upvotes: 4

Related Questions