Edit: Ok, this was a disaster of a question. I'll make sure to use timeit
in the future
I solved a Codewars problem that had the user check if a number was a palindrome, was incrementing, and etc. After I solved it, I noted how the top solutions were much more simple, intuitive, and elegant than mine, although they were less efficient. I figured this was because code golf is more important in Codewars than efficiency, but after Googling around it seemed to me that perhaps a logically intuitive and elegant solution was more important in Python than an efficient but less elegant solution. Is there any truth to this?
To make this post more appropriate for the scope of Code Review, I will include two solutions for two problems, is_palindrome
and is_incrementing
. The first solution is the more elegant and logically intuitive one, and the second solution is my attempt at a more efficient one. I would like to know which solution is more appropriate for Python, and also what improvements could be made to my solution.
In Python, it is regularly suggested to use the following to determine if a string is a case-sensitive palindrome:
def is_palindrome(word):
return word == word[::-1]
Here is my attempt at a more efficient way to accomplish this:
def is_palindrome(word):
low = 0
high = len(word) - 1
while low < high:
if word[low] != word[high]:
return False
low += 1
high -= 1
return True
As another example, to determine if a number is incrementing, such as 234
but not 231
it is suggested to use:
def is_incrementing(number):
return str(number) in '0123456789'
Instead of something like:
def is_incrementing(number)
number = str(number)
prev = number[0]
for char in number[1:]:
if int(char) != int(prev) + 1:
return False
prev = str(int(prev) + 1)
return True
is_palindrome
took 1/4 the amount of time as your 'efficient' one, when I timed them. \$\endgroup\$ – Peilonrayz Nov 13 '16 at 23:05first = str(int(first) + 1)
, which makes no sense, intoprev = char
, youris_incrementing
is (again) 4 times slower than the first one. Even trying to be smart by not converting back and forth between strings and integer but rather using division and modulus, you end up with something 3 times slower thanstr(number) in '0123456789'
. \$\endgroup\$ – 301_Moved_Permanently Nov 14 '16 at 0:23