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?

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! 

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

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. 

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

Top 13 Highest Paying Data Science Jobs in India [A Complete Report]
905265
In this article, you will learn about Top 13 Highest Paying Data Science Jobs in India. Take a glimpse below. Data Analyst Data Scientist Machine
Read More

by Rohit Sharma

12 Apr 2024

Most Common PySpark Interview Questions & Answers [For Freshers & Experienced]
20925
Attending a PySpark interview and wondering what are all the questions and discussions you will go through? Before attending a PySpark interview, it’s
Read More

by Rohit Sharma

05 Mar 2024

Data Science for Beginners: A Comprehensive Guide
5068
Data science is an important part of many industries today. Having worked as a data scientist for several years, I have witnessed the massive amounts
Read More

by Harish K

28 Feb 2024

6 Best Data Science Institutes in 2024 (Detailed Guide)
5179
Data science training is one of the most hyped skills in today’s world. Based on my experience as a data scientist, it’s evident that we are in
Read More

by Harish K

28 Feb 2024

Data Science Course Fees: The Roadmap to Your Analytics Career
5075
A data science course syllabus covers several basic and advanced concepts of statistics, data analytics, machine learning, and programming languages.
Read More

by Harish K

28 Feb 2024

Inheritance in Python | Python Inheritance [With Example]
17647
Python is one of the most popular programming languages. Despite a transition full of ups and downs from the Python 2 version to Python 3, the Object-
Read More

by Rohan Vats

27 Feb 2024

Data Mining Architecture: Components, Types & Techniques
10803
Introduction Data mining is the process in which information that was previously unknown, which could be potentially very useful, is extracted from a
Read More

by Rohit Sharma

27 Feb 2024

6 Phases of Data Analytics Lifecycle Every Data Analyst Should Know About
80777
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]
139137
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

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