1
\$\begingroup\$

This code checks if the given integer is a palindrome. If it is, prints given integer is a palindrome else, not a palindrome:

from collections import deque
def polindrome(input):
 d = deque()
 d.extendleft(str(input))
 result = int(''.join(d))
 if input == result :
     return input , 'is a polindrome'
 else :
     return (input , 'is not a polindrome')
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

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. deques 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?)

\$\endgroup\$
1
  • \$\begingroup\$ Thank you, Bailey, my intention is to use collections and deque as part of learning different ways of solving the same problem. Your insight into solving the same problem in simpler ways made me to understand to write the code better way. \$\endgroup\$
    – Suresh2019
    Commented Feb 3, 2019 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.