alicew
alicew

Reputation: 275

Why wouldn't this palindrome test work?

A palindrome is a string that reads the same forwards and backwards. Examples of palindromes include "lol", "abba", "radar", and "pickle elkcip". Indicate whether or not it works under all circumstances described in the following docstring: '''Return True if string s is a palindrome and return False otherwise.'''

def palindrome2(s):
    n = len(s)
    pal = True
    for i in range(n/2):
        if s[i] == s[n-i-1]:
            pal = True
        else:
            pal = False
    return pal

I don't get why this function wouldn't work. To me, it seems as if the function works. Apparently, the booleans are misused but I don't get how the booleans above are not used properly. Can someone please explain this to me?

Upvotes: 3

Views: 251

Answers (4)

rbanffy
rbanffy

Reputation: 2521

@ulmangt's solution is very clever, but I'd go with a less enigmatic:

def palindrome(s):
    return all(( s[i] == s[-(i+1)] for i in range(len(s)/2) ))

At least it does half as many comparisons ;-)

Upvotes: 3

Levon
Levon

Reputation: 143047

The way the body of the loop is coded the values of pal may change between True and False repeatedly depending on whether a given pair of characters happen to match or not during that particular iteration.

Better to check for inequality, set your Boolean variable pal to False and drop out of the loop immediately then.

Something like this:

def palindrome2(s):
    n = len(s)
    pal = True

    for i in range(n/2)
        if s[i] != s[n-i-1]: # the moment it's false
           pal = False       # set pal and
           break             # drop out of the loop

    return pal

alternatively, without using a Boolean variable:

    ...
    for i in range(n/2)
        if s[i] != s[n-i-1]: # the moment it's false
           return False      # exit the function by returning False

    return True  # otherwise return True

Upvotes: 6

ulmangt
ulmangt

Reputation: 5423

For fun, you could also try the much simpler:

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

(exercise left to the reader regarding how it works)

Upvotes: 8

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

You always check every single character. You need to return as soon as you know the result definitively.

Upvotes: 3

Related Questions