How To Check Palindrome Number in Python?
Updated on Mar 04, 2024 | 10 min read | 15.9k views
Share:
For working professionals
For fresh graduates
More
Updated on Mar 04, 2024 | 10 min read | 15.9k views
Share:
As someone well-versed in Python programming, I’ve often encountered the task of checking for palindromes using Python. In this article, I’ll guide you through the process of determining whether a number is a palindrome or not. But first, let’s understand what exactly a palindrome is and why it’s important to be able to identify them in programming. Palindromes are numbers or strings that read the same forwards and backwards. They are common in coding interviews and have various applications in real-world scenarios. By mastering the technique of checking for palindromes using Python, you’ll enhance your problem-solving skills and be better prepared for coding challenges in your career. Let’s dive in and explore how to tackle palindromes using Python!
A palindrome is a word, number, or any string of characters which reads the same backward as it reads forward.
You may have to check whether a number is a palindrome or not in everyday programming and competitive programming. It is straightforward to reverse a number and check it. However, you need to perform the one-liner logic to check readability and reduce the lines of code. From the following examples, you can understand what a palindrome number in python is.
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.
A slicing method helps you determine the reverse. You can also use the built-in ‘’.join(reversed()). There are several other ways to reverse a string, but the following section discusses a simple palindrome number program in python.
This program compares the reversed string with the original string. It returns “True” if both the strings are equal, else it returns “False”.
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.
Read: Python Project Ideas & Topics
How does Palindrome work in Python?
The function’s argument is considered and its reverse is determined. This is then stored in a separate variable. The length technique helps determine the reverse.
This step determines the variable’s length, and a manual reverse is employed on top of the length.
The actual variable and variable with reverse stored are compared to determine whether they contain the same value. palindrome number in python
The “True” value is returned from the function if both values are matched. The “False” value is returned from the function if both the values don’t match.
The message “The string is a palindrome” is printed when the value is “True”. The message “The string is not a palindrome” is printed when the value is “False”.
Methods to find Palindrome in Python:
1) Without determining the reverse of the string:
It constantly compares the characters present at the first and last index of the string. The comparison continues until they are unequal.
The following section discusses this method with the help of two examples.
Example-1:
String value “malayalam”:
It compares the first and last characters and they are equal. It then compares the second and second last characters and they are equal. The process in this palindrome number program in python continues until all characters are checked this way. Hence, the string is a palindrome.
Example-2:
String value “shops”:
Only the first and last characters are equal. When the second and second last characters are compared, they are found unequal. So, it is not a palindrome.
You can implement this idea through two pointers or recursion. Let’s first implement using pointers. You begin with the start pointer 0 and the end pointer at the last index. The comparison goes on and if characters are equal, the start pointer is incremented and the end pointer is decremented.
The question that arises in this palindrome number python is when to return False. There is no need to look for subsequent indexes, so “False” is returned if the characters for any set of pointers are unequal.
When to return “True” in the palindrome number program in python? If a string is a Palindrome, “True” is returned when both the pointers are equal, or the start pointer surpasses the end pointer and returns true.
For Loop to check for Palindrome in Python:
You can use the “For” loop in Python to loop over a string in reverse order. Let’s check how to use the “For” loop to check for the palindrome number program in python.
s = 'Poor Dan is in a droop'
def palindrome(s):
s = s.lower().replace(' ', '')
reversed_string = ''
for i in range(len(s), 0, -1):
reversed_string += s[i-1]
return a_string == reversed_string
print(palindrome(s))
# Returns: True
The output of the above program shows that the entered string is Palindrome.
checkPalindrome() method to check for Palindrome in Python:
The checkPalindrome()is a user-defined method that accepts a value and returns a value if the reciprocal equals the element itself. So, we accepted the number provided by the user as a parameter to the checkPalindrome()method. The return variable is therefore initialized with the variable “chck”. When comparing the values of the variable “chck”, if it contains 1, it means the given value is a palindrome. Otherwise, the entered value is not a palindrome.
For example, if the entered number is “987569”. After reversing the number, it is compared to the originally entered number. But they both are not equal. So, “987569” is not a palindrome number.
reversed() method to check for Palindrome in Python:
The reversed() function in Python determines whether the entered value or string is a palindrome or not. It accepts a series of characters and returns the inverse iterator. Instead of the list catalog [::-1], reversed() method is used to inverse the series of values within the string. The real and inverted string is compared elements by elements. Finally, it determines whether the number is palindrome or not.
Code for the reversed() method to check for palindrome number python:
w = input()
if str(w) = = “” . join (reversed(w))
print (“It is a palindrome”)
else
print (“It is not a palindrome)
For example, you can use the reversed() method to check if the string “nayan” is a palindrome or not. Firstly, the “.join (reversed () function” helps to analyze the inverse of the real string. The “==” equation operator is used to compare both the real string and the inverse string. The message “It is a palindrome” is printed if the real string and the reverse string are equal.
The fastest way to check if a string is Palindrome or not in Python:
The fastest way to check for a palindrome number python is string indexing. It can work up to 70 times faster than a “For” loop.
Also, Check out all Trending Python Tutorial Concepts in 2024.
#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.
upGrad’s Exclusive Data Science Webinar for you –
ODE Thought Leadership Presentation
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”)
Our learners also read: Top Python Courses for Free
I hope you will understand how to check for palindromes using Python is a valuable skill. Palindromes are words or numbers that read the same backward and forward. By practicing common palindrome-related coding questions, we strengthen our Python skills and become better problem solvers. Being able to identify palindromes helps us in coding interviews and real-world situations. Keep practicing and applying what you’ve learned, and I am sure you’ll be well-prepared to tackle any palindrome-related challenges that come your way.
If you are curious to learn about data science, I strongly recommend you to check out IIIT-B & upGrad’s Executive PG Programme in Data Science which is created f 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.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources