Using Python, reverse an integer, and tell if palindrome Using Python, reverse an integer, and tell if palindrome python python

Using Python, reverse an integer, and tell if palindrome


def palindrome(num):    return str(num) == str(num)[::-1]


Integer numbers don't have len().

Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).

To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):

def reverse(num):  rev = 0  while num > 0:    rev = (10*rev) + num%10    num //= 10  return rev

Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):

def reverse(num):  return int(str(num)[::-1])


This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.

def reverse(i):    return int(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))def is_palindrome(i):    return i == reverse(i)

It works for integer i ≥ 0.

Note that reverse(123) == reverse(1230) == 321. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.

Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.