Why wouldn't this palindrome test work?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 Why Wouldn'T This Palindrome Test Work?
00:43 Answer 1 Score 8
00:59 Accepted Answer Score 6
01:47 Answer 3 Score 3
02:04 Answer 4 Score 3
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/1029...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping
--
Chapters
00:00 Why Wouldn'T This Palindrome Test Work?
00:43 Answer 1 Score 8
00:59 Accepted Answer Score 6
01:47 Answer 3 Score 3
02:04 Answer 4 Score 3
02:21 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 ;-)