There's a much easier way to do this. Python slicing allows you to reverse a string with s[::-1]
. So you can just do:
def is_palindrome(s):
return s == s[::-1]
To make this work for integers, you can just str()
the int.
Why would you want to do it this way? For one, you're already converting to a string. So this approach shouldn't have any worse performance characteristics. Your use of a deque
here is probably a bit overkill. deque
s make sense when you have lots of prepending to lists. Here, your numbers aren't likely to be that many digits (even though integers in python can be arbitrarily large). And then on top of this you then convert back to an int
, which is an unnecessary step (as you could just compare the strings) and could fail (although it shouldn't).
And beyond the performance, using the deque
(and converting back to an int
) makes it more difficult to understand what your code is doing. s[::-1]
is a well understood idiom that clearly conveys its purpose in context (s == s[::-1]
).
I wouldn't return a tuple from the function. It's much more informative to return a bool
and then use that to print whatever string you want:
if is_palindrome(str(num)):
print(f'{num} is a palindrome')
else:
print(f'{num} is not a palindrome')
You should also look into PEP8 to make your code look more consistent with Python's widely accepted style guide.
Looking at the performance:
$ python3 -m timeit -s 'from funcs import polindrome' 'polindrome(123456654321)'
200000 loops, best of 5: 1.26 usec per loop
$ python3 -m timeit -s 'from funcs import is_palindrome' 'is_palindrome(str(123456654321))'
500000 loops, best of 5: 435 nsec per loop
is_palindrome
is about 2.8 times faster.
You may also want to write some unit tests as there are some strange cases that your code may not handle correctly (eg. should 120
be a palindrome of 21
since 021 == 21
or not since they are different lengths?)