简体   繁体   中英

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?

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)

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

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

@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 ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM