Programs

# How To Check Palindrome Number in Python?

## What is a Palindrome?

A palindrome is a word, number, or any string of characters which reads the same backward as it reads forward.

Few examples: detartrated, 1567651, 02/02/2020, Malayalam

So this article shows you various ways you can write a program to check whether a given input is a palindrome or not, using Python.

Method 1:

The most naïve solution which comes to mind is to reverse the number and check if it equals the input number. It can be done as follows:

number = int(input());

reverse = 0

while number > 0:

digit = number % 10

reverse = reverse * 10 + digit

number = number // 10

if number==reverse:

print(“it is a palindrome!”)

else:

print(“it is not a palindrome!”)

However, this compromises the readability of the code and has more lines of code than required. Checkout our online data science course to learn more.

Here’s a short and sweet way to check a number using just one line.

Method 2:

The trick is to take the input number as a str data type instead of int. Then you can use the [::-1] slicing technique to obtain the reverse of a string and check for equality in the if statement itself.

number = input()

if number == number[::-1]:

print(“it is a palindrome!”)

else:

print(“it is not a palindrome!”)

Method 3:

This is a recursive method to check if an array is a palindrome or not.

def isPalindrome(numbers, start, end):

if start >= end:

return True

if numbers[start] == numbers[end]:

return isPalindrome(numbers, start + 1, end – 1)

else:

return False

numbers= list(map(int, input().split()))

n=len(numbers)

if isPalindrome(numbers, 0, n-1):

print(“it is a palindrome!”)

else:

print(“it is not a palindrome!”)

The isPalindrome function checks whether the first and last array elements are same or not. If not, the function immediately returns False. Otherwise it recursively checks for the next extreme elements till the two pointers meet in the middle.

## Common coding interview questions related to palindromes

#1 Longest palindromic Substring

Given only one string as an input, you have to return the length of the longest palindromic substring in the string.

Eg:

Input: ‘acbcbabcc’

Output: 5  (‘cbabc’)

Approach:

If we try to relate this to one of the most common problems of DP, the longest common substring, here the difference is that we are given only one input string whereas LCS uses two strings. Since we know a palindrome is exactly equal to its reverse, we can make the second string as the reverse of our given input.

Now this becomes exactly the same as finding LCS.

def LCSubstr(A, B, m, n):

LCSub = [[0 for i in range(n+1)] for j in range(m+1)]

ans = 0

for i in range(m+1):

for j in range(n+1):

if (i == 0 or j == 0):

LCSub[i][j] = 0

elif A[i-1] == B[j-1]:

LCSub[i][j] = 1 + LCSub[i-1][j-1]

ans = max(ans, LCSub[i][j])

else:

LCSub[i][j] = 0

return ans

str1 = input()

str2 = str1[::-1]

m = len(str1)

n = len(str2)

print(‘Length of longest palindromic substring = ‘, LCSubstring(str1, str2, m, n))

So for the above input, we obtain the two strings as

‘acbcbabcc’ and

‘ccbabcbca’

The longest common substring becomes ‘cbabc’ which is of length 5.

#2 Check if an Anagram of a String is a Palindrome

Given a string as an input, you have to check if any anagram of the string can be a palindrome or not and return yes/no accordingly.

Eg:

Input: ‘pythonpython’

Output: Yes

(while the string itself is not a palindrome, a possible anagram ‘pythonnohtyp’ does form a palindrome)

Input: ‘harrypotter’

Output: No

Approach:

If you notice carefully, whenever we have a palindrome string of even length, all the characters in the first half are repeated in the second half. This means all characters present in the string occur an even number of times.

When the length is odd, all characters to the left of the middle element (not inclusive) occur the same number of times in the right side of the middle element. This means there is only one character which occurs an odd number of times (middle element) and all the others occur even number of times.

Using this logic, we can store the count of the characters in the string in a hash and check for these constraints to get the required answer.

CHAR_RANGE = 256

str1 = input()

freq = [0 for i in range(CHAR_RANGE)]

for i in str1:

freq[ord(i)] += 1  #ord(x) gives the unicode value of x

num_odds = 0

for i in range(CHAR_RANGE):

if freq[i] & 1:

num_odds += 1

if (num_odds > 1):

print(“Yes”)

else:

print(“No”)

## Conclusion

In conclusion, the palindrome problems are very common and interesting. They are useful to solve various mathematical puzzles and competitive programming questions.

If you are curious to learn about data science, check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created for working professionals and offers 10+ case studies & projects, practical hands-on workshops, mentorship with industry experts, 1-on-1 with industry mentors, 400+ hours of learning and job assistance with top firms.

## What is the time complexity of the Palindrome program?

The number of elementary operations done by the method is often used to estimate time complexity, assuming that each elementary process takes a set amount of time to complete. The time complexity of determining whether or not a number is a palindrome is O(log10 (n)). When we check for the values to be a palindrome, we divide the number or value by ten in each iteration. As a result, the temporal complexity is equal to the number of digits in a number.

## How is / different from // operator in Python?

When we use the divide operator, i.e., a single slash (/) in Python, the compiler simply divides the two values on the right and left sides of the slash. But when we use double slash(//), i.e., floor division, we ask the compiler to carry out the typical division process, but the result it yields is the biggest integer possible close to the answer. This integer is either less than or equal to the result of normal division.

## What is the entry-level salary of a Python Developer?

It's a well-known fact that Python is widely used in most industries and companies, making Python the second-highest-paid computing language. Python is also the favorite programming language amongst students and professionals because it is easy to learn and is highly flexible. The entry-level salary of a Python Developer in India is around INR 4,27,293 per annum on average. Professionals learning Python have a lot of scope as Python is also used in other fields such as Data Science and Machine Learning. ## Prepare for a Career of the Future

Be a Certified Data Scientist - Advanced Certificate Programme in Data Science