The Python Oracle

What possible improvements can be made to a palindrome program?

--------------------------------------------------
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: Magical Minnie Puzzles

--

Chapters
00:00 What Possible Improvements Can Be Made To A Palindrome Program?
00:49 Accepted Answer Score 9
01:03 Answer 2 Score 3
01:17 Answer 3 Score 1
01:27 Answer 4 Score 3
02:28 Thank you

--

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

--

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

--

Tags
#python #palindrome

#avk47



ACCEPTED ANSWER

Score 9


I think the best way to improvise write a palindrome checking function in Python is as follows:

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

(Add the lower() call as required.)




ANSWER 2

Score 3


What about something way simpler? Why are you creating a class instead of a simple method?

>>> is_palindrome = lambda x: x.lower() == x.lower()[::-1]
>>> is_palindrome("ciao")
False
>>> is_palindrome("otto")
True



ANSWER 3

Score 3


While other answers have been given talking about how best to approach the palindrome problem in Python, Let's look at what you are doing.

You are looping through the string by using indices. While this works, it's not very Pythonic. Python for loops are designed to loop over the objects you want, not simply over numbers, as in other languages. This allows you to cut out a layer of indirection and make your code clearer and simpler.

So how can we do this in your case? Well, what you want to do is loop over the characters in one direction, and in the other direction - at the same time. We can do this nicely using the zip() and reversed() builtins. reversed() allows us to get the characters in the reversed direction, while zip() allows us to iterate over two iterators at once.

>>> a_string = "something"
>>> for first, second in zip(a_string, reversed(a_string)):
...     print(first, second)
... 
s g
o n
m i
e h
t t
h e
i m
n o
g s

This is the better way to loop over the characters in both directions at once. Naturally this isn't the most effective way of solving this problem, but it's a good example of how you should approach things differently in Python.




ANSWER 4

Score 1


One improvement I can see would be to use xrange instead of range.