Nearest palindrome of a number in python

In this tutorial, we will see how to generate the nearest palindrome of a given number in Python if the given number is not a palindrome. By the end of this tutorial, you will be able to find the nearest palindrome with very simple and easy code. So, let’s begin the tutorial.

Nearest Palindrome in Python

A palindrome may be a string or a number that reads the same from both ends, i.e. if we reverse a word, it should be the same as the original word. Some of the examples of palindromes are madam, 101, etc.

In python, we check whether the given number or string is a palindrome by using the slicing operator. For generating the nearest palindrome of a number also we will be using the slicing operator. The nearest palindrome of a given number is obtained by adding 1 to the number until it is a palindrome. This is done by using a while loop recursively. When the condition is met, the number is given as output. The working code for the above is given as:

def palin(n):
        if n==int(str(n)[::-1]):
            return n

Here first, we typecast the integer to string because we cannot use the slice operator on an integer. Then we typecast the string to an integer because we have to iterate the loop further by adding 1 if it is not a palindrome.

Suppose we give the input as 1456, the output will be
Suppose we give the input as 2766236, the output will be

You can demonstrate the code by taking various numbers as input

Leave a Reply

Your email address will not be published.