Python program to check if a number is palindrome (one line)

Python Methods and Functions

Sometimes we have an application that checks a number for palindrome or not, and this is quite common in everyday programming or concurrent programming, it is easy to rotate a number and check it, but sometimes for readability and to shorten lines of code, we need to do this in a single line logic. Let's discuss some of the ways this can be achieved.

Input: test_number = 12321
Output: True

Input: test_number = 1234
Output : False

Method # 1: Using math.log () + recursion + list comprehension
Combination of the above three functions can easily accomplish this particular task, the logs function extracts the number of digits that are fed from 10 to get the number for this iteration to compare. The process is repeated to check for palindrome.

# Python3 code for demonstration
# checking the number is palindrome
# using math.log () + recursion + list comprehension

import math

 
# recursive function for reverse

def rev (num):

return int (num ! = 0 ) and ((num % 10 ) *

( 10 * * int (math.log (num, 10 ))) +

rev (num / / 10 ))

 
# initialization number

test_number = 9669669

 
# print original number

< code class = "keyword"> print ( "The original number is:" + str (test_number))

  
# using math.log () + recursion + list comprehension
# to check the number palindrome

res = test_number = = rev (test_number)

 
# print result

print ( "Is the number palindrome? : " + str (res))

Exit:

 The original number is: 9669669 Is the number palindrome?: True 

Method # 2: Using str () + slicing strings
This can also be done by converting a number to a string, and then flipping it using the string slicing method and comparing it, which returns the answer if true.

# Python3 demo code
# checking the number is a palindrome
# using str () + string slicing

 
# initialization number

test_number = 9669669

 
# print original number

print ( "The original number is:" + str (test_number))

 
# using str () + line slicing
# to check the number of palindrome

res = str (test_number) = = str (test_number) [:: - 1 ]

 
# print result

print ( "Is the number palindrome? : " + str (res))

Exit:

 The original number is: 9669669 Is the number palindrome?: True 




Get Solution for free from DataCamp guru