The Python Oracle

Why wouldn't this palindrome test work?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: A Thousand Exotic Places Looping v001

--

Chapters
00:00 Question
00:59 Accepted answer (Score 6)
01:52 Answer 2 (Score 8)
02:10 Answer 3 (Score 3)
02:30 Answer 4 (Score 3)
02:47 Thank you

--

Full question
https://stackoverflow.com/questions/1029...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ANSWER 1

Score 8


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)




ACCEPTED ANSWER

Score 6


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



ANSWER 3

Score 3


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




ANSWER 4

Score 3


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