We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details

Palindrome Number in Python

Ayushi Trivedi 06 Jun, 2024
5 min read

Introduction

Palindrome numbers those numbers that are same both as forward and backward. Because of this unique fact, it is an intriguing subject in mathematics. Their distinct qualities have captivated mathematicians, programmers, and educators alike. This article examines several approaches to Python palindrome number checking, from basic text manipulation to more complex recursive algorithms. Furthermore, we explore their real-world applications in several domains, showcasing their significance in computer science, mathematics, and other areas.

Overview

  • Explore palindrome numbers and the traits that make them unique.
  • Learn how to use recursion, half comparison, string manipulation, number reversal, and other methods to determine if a given number in Python is a palindrome.
  • Gain expertise in using Python’s palindrome checking techniques by working through real-world scenarios and short code samples.
  • Examine the real-world uses for palindrome numbers in data validation, computer science, mathematics, and cryptography.
palindrome number

What is Palindrome Number?

A number that reads the same both forward and backward is called a palindrome. For example, the number 121 is a palindrome since it still equals 121 even if the digits are reversed. 1331 is an additional example.

A number must meet the requirement that the same number is obtained by reversing its digits in order to be considered a palindrome.

Some key points about palindrome numbers:

  • By definition, numbers with only one digit (such as 1, 2, 3,…, 9) are palindromes.
  • Whether a palindrome is read from left to right or from left to right, it remains the same.
  • In number discourse, negative numbers are usually not regarded as palindromes.

Steps to Check Palindrome Number in Python

Let’s examine the fundamental steps needed to determine if a given number is a palindrome.

  • Step1: Convert the Number to a String.
  • Step2: Reverse the String.
  • Step3: Compare the Original and Reversed Strings.
  • Step4: Return the Result.

Python Program to Check Palindrome Number

Let’s create a program that checks if a given number is an Palindrome number using Python.

def palindrome_number(n):
    temp = n
    rev = 0
    while n > 0:
        dig = n % 10
        rev = rev * 10 + dig
        n = n // 10
    return temp == rev

# Input from user
n = int(input("Enter number: "))

# Checking if the number is palindrome
if palindrome_number(n):
    print("Number is a palindrome!")
else:
    print("Number isn't a palindrome!")

Output:

Enter number: 121
Number is a palindrome!

Methods to Calculate Palindrome Number

We have multiple methods using which we can find Palindrome number. Let us look into those methods one by one in detail with code and their output.

Using String Manipulation

This method converts the number to a string and checks if the string is equal to its reverse.

Pros:

  • Easy and simple to understand.
  • Directly uses Python’s string manipulation capabilities.

Cons:

  • Requires additional space to store the string representation of the number.
def is_palindrome_string(n):
    num_str = str(n)
    return num_str == num_str[::-1]

print(is_palindrome_string(121))   
print(is_palindrome_string(1331))  
print(is_palindrome_string(12321))
print(is_palindrome_string(12345)) 

Output:

True
True
True
False

Reversing the Number

This method reverses the number itself and checks if the reversed number is equal to the original number.

Pros:

  • Effective in terms of complexity in both space and time.
  • Directly manipulates the number without converting it to another data type.

Cons:

  • Modifies the original input number.
def is_palindrome_reverse_number(n):
    original = n
    reversed_num = 0
    while n > 0:
        last_digit = n % 10
        reversed_num = reversed_num * 10 + last_digit
        n //= 10
    return original == reversed_num
print(is_palindrome_reverse_number(121))   
print(is_palindrome_reverse_number(1331))  
print(is_palindrome_reverse_number(12321)) 
print(is_palindrome_reverse_number(12345)) 

Output:

True
True
True
False

Comparing Half of the Number

This method reverses only half of the number and compares it with the other half.

Pros:

  • Optimized for space efficiency by reversing only half of the number.
  • Handles both odd and even length numbers.

Cons:

  • More complex logic compared to other methods.
def is_palindrome_half_number(n):
    if n < 0 or (n % 10 == 0 and n != 0):
        return False
    
    reversed_num = 0
    while n > reversed_num:
        reversed_num = reversed_num * 10 + n % 10
        n //= 10
    
    return n == reversed_num or n == reversed_num // 10
print(is_palindrome_half_number(121))
print(is_palindrome_half_number(1331)) 
print(is_palindrome_half_number(12321)) 
print(is_palindrome_half_number(12345))

Output:

True
True
True
False

Using Recursion

This method compares digits recursively to determine if a given integer is a palindrome.

Pros:

  • demonstrates how to solve the problem using recursion.
  • Efficient in terms of space usage.

Cons:

  • greater in complexity and might be more difficult for novices to grasp.
def is_palindrome_recursion(n):
    def helper(n, original):
        if n == 0:
            return original == 0
        if helper(n // 10, original) and (n % 10 == original % 10):
            original //= 10
            return True
        else:
            return False
    
    if n < 0:
        return False
    return helper(n, n)
print(is_palindrome_recursion(121))   
print(is_palindrome_recursion(1331))  
print(is_palindrome_recursion(12321))
print(is_palindrome_recursion(12345))

Output:

True
True
True
False

Checking Half and Mirror

This method optimizes the process by only reversing half of the number and comparing it with the other half.

Pros:

  • Optimized for space efficiency by reversing only half of the number.
  • Handles both odd and even length numbers.

Cons:

  • More complex logic compared to other methods.
def is_palindrome_half_and_mirror(n):
    if n < 0 or (n % 10 == 0 and n != 0):
        return False
    
    reversed_num = 0
    while n > reversed_num:
        reversed_num = reversed_num * 10 + n % 10
        n //= 10
    
    return n == reversed_num or n == reversed_num // 10
print(is_palindrome_half_and_mirror(121))   
print(is_palindrome_half_and_mirror(1331))  
print(is_palindrome_half_and_mirror(12321)) 
print(is_palindrome_half_and_mirror(12345)) 

Output:

True
True
True
False

Applications of Palindrome Numbers

Palindrome numbers have several applications in various fields. Here are some of the notable applications:

  • Number Systems and Representation: Palindrome numbers are used in digital electronics and computers to test algorithms and systems that translate numbers between different bases.
  • Mathematical Puzzles: In recreational mathematics and puzzles, enthusiasts frequently use palindromic integers as challenges to find the largest or smallest palindrome within a given range and to determine attributes such as the sum of the digits.
  • Error Checking and Data Verification: Palindrome sequences can be employed in data storage and communication as a component of error-checking algorithms to guarantee data integrity.
  • Educational Purposes: Palindromic numbers serve as useful examples for educators to teach symmetry and patterns in numbers as well as algorithmic thinking in programming.
  • Numerical Algorithms: Palindromic numbers sometimes serve as a testing and verification tool for algorithms that deal with number sequences and properties.

Conclusion

This article examines various Python methods for determining if a given integer is a palindrome. It talks about real-world uses for palindrome numbers, including data verification, encryption, and instructional games. Every approach has benefits and is appropriate in certain situations. Readers’ comprehension of palindrome numbers improves their ability to solve problems and reason algorithmically in Python by gaining insights into symmetry and patterns in numbers.

If you want to learn basics of python for free, checkout our Introduction to Python Program today!

Frequently Asked Questions

Q1. What is a palindrome number?

A. A number that reads the same backward as forward is known as palindrome number. For example, 121 and 1331 are palindrome numbers.

Q2. Do negative numbers count as palindrome numbers?

A. No, in the context of palindrome numbers, we typically do not consider negative numbers as palindromes.

Q3. Are single-digit numbers considered palindrome numbers?

A. Yes, single-digit numbers like 0, 1, 2, …, 9 are considered palindromes because they read the same backward and forward.

Q4. What are some examples of palindrome numbers?

A. Some examples of palindrome numbers include 121, 1331, 12321, 9009, etc.

Ayushi Trivedi 06 Jun, 2024

My name is Ayushi Trivedi. I am a B. Tech graduate. I have 3 years of experience working as an educator and content editor. I have worked with various python libraries, like numpy, pandas, seaborn, matplotlib, scikit, imblearn, linear regression and many more. I am also an author. My first book named #turning25 has been published and is available on amazon and flipkart. Here, I am technical content editor at Analytics Vidhya. I feel proud and happy to be AVian. I have a great team to work with. I love building the bridge between the technology and the learner.