Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconData Sciencebreadcumb forward arrow iconHow To Check Palindrome Number in Python?

How To Check Palindrome Number in Python?

Last updated:
20th Sep, 2022
Views
Read Time
10 Mins
share image icon
In this article
Chevron in toc
View All
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.

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.

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.

Read our popular Data Science Articles

#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

Top Data Science Skills to Learn

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.

Profile

Rohit Sharma

Blog Author
Rohit Sharma is the Program Director for the UpGrad-IIIT Bangalore, PG Diploma Data Analytics Program.

Frequently Asked Questions (FAQs)

1What 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.

2How 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.

3What 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.

Explore Free Courses

Suggested Blogs

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
78131
What is a Data Analytics Lifecycle? Data is crucial in today’s digital world. As it gets created, consumed, tested, processed, and reused, data goes
Read More

by Rohit Sharma

19 Feb 2024

Sorting in Data Structure: Categories & Types [With Examples]
135412
The arrangement of data in a preferred order is called sorting in the data structure. By sorting data, it is easier to search through it quickly and e
Read More

by Rohit Sharma

19 Feb 2024

Data Science Vs Data Analytics: Difference Between Data Science and Data Analytics
66831
Summary: In this article, you will learn, Difference between Data Science and Data Analytics Job roles Skills Career perspectives Which one is right
Read More

by Rohit Sharma

19 Feb 2024

13 Exciting Python Projects on Github You Should Try Today [2023]
44246
Python is one of the top choices in programming languages among professionals worldwide. Its straightforward syntax allows software developers and dat
Read More

by Hemant

19 Feb 2024

Top 15 Python AI & Machine Learning Open Source Projects
35836
Machine learning and artificial intelligence are some of the most advanced topics to learn. So you must employ the best learning methods to make sure
Read More

by Pavan Vadapalli

19 Feb 2024

Top 21 Python Developer Skills You Must Need To Become a Successful Python Developer
78133
Its intuitive syntax, extensive libraries and versatile integration capabilities have fueled incredible growth across web development and scientific c
Read More

by Rohit Sharma

19 Feb 2024

Most Frequently Asked NumPy Interview Questions and Answers [For Freshers]
28509
If you are looking to have a glorious career in the technological sphere, you already know that a qualification in NumPy is one of the most sought-aft
Read More

by Rohit Sharma

19 Feb 2024

Top 30 Python Pattern Programs You Must Know About
33160
Summary Pattern in Python or “Python patterns” is an essential part of Python programming, especially when you are just starting out with using algor
Read More

by Rohit Sharma

19 Feb 2024

Top 12 Fascinating Python Applications in Real-World [2024]
154536
It is a well-established fact that Python is one of the most popular programming languages in both the coding and Data Science communities. But have y
Read More

by Rohit Sharma

19 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon