Sometimes, we have an application of checking a number is palindrome or not and it’s quite common while day-day programming or competitive programming, it’s easy to reverse a number and check it but sometimes for readability and reducing lines of code, we require to perform this in one-liner logic. Let’s discuss certain ways in which this can be achieved.
Input : test_number = 12321
Output : TrueInput : test_number = 1234
Output : False
Method #1 : Using math.log()
+ recursion + list comprehension
The combination of above three functions can perform this particular task easily, the logs function extracts the number of digits which is powered by 10 to get the number for that iteration for comparison. The process is recurred to test for palindrome.
# Python3 code to demonstrate # checking a number is palindrome # using math.log() + recursion + list comprehension import math # the recursive function to reverse def rev(num): return int (num ! = 0 ) and ((num % 10 ) * \ ( 10 * * int (math.log(num, 10 ))) + \ rev(num / / 10 )) # initializing number test_number = 9669669 # printing the original number print ( "The original number is : " + str (test_number)) # using math.log() + recursion + list comprehension # for checking a number is palindrome res = test_number = = rev(test_number) # printing result print ( "Is the number palindrome ? : " + str (res)) |
The original number is : 9669669 Is the number palindrome ? : True
Method #2 : Using str()
+ string slicing
This can also be done by converting the number into a string and then reversing it using the string slicing method and comparing it, truth of which returns the answer to it.
# Python3 code to demonstrate # checking a number is palindrome # using str() + string slicing # initializing number test_number = 9669669 # printing the original number print ( "The original number is : " + str (test_number)) # using str() + string slicing # for checking a number is palindrome res = str (test_number) = = str (test_number)[:: - 1 ] # printing result print ( "Is the number palindrome ? : " + str (res)) |
The original number is : 9669669 Is the number palindrome ? : True
We can also read input as string and then simply check for palindrome.
num = input ( "Enter a number" ) if num = = num[:: - 1 ]: print ( "Yes its a palindrome" ) else : print ( "No, its not a palindrome" ) |
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.