Why not try this palindrome test?

A palindrome is a line that reads the same back and forth. Examples of palindromes include lol, abba, radar, and pickle elkcip. Indicates whether it works under all circumstances described in the following documentation: '' 'Return True if string s is a palindrome and returns 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 do not understand why this function does not work. It seems to me that the function works. Booleans seem to be used incorrectly, but I don't understand how the booleans above are not used properly. Can someone please explain this to me?

+3
source share
4 answers

, pal True False , .

, pal False .

- :

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

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

    return pal

, :

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

    return True  # otherwise return True
+6

:

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

( , )

+8

. , .

+3

@ulmangt , :

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

, , ; -)

+3