Palindrome Program in Python

Problem Description

Write a Python Program to check whether a given number is a palindrome.

What is Palindrome?

Palindrome number in Python is a number that remains the same when its digits are reversed. It reads the same forwards and backwards. To check if a number is a palindrome, we compare it with its reverse. If they are equal, the number is a palindrome.

Example: Numbers like 121, 454, and 888 are all palindrome numbers as they read the same forwards and backwards.

Problem Solution

There are several ways to check whether a number is a palindrome or not in Python. Let’s explore various approaches to implement this function:

Palindrome Number Program in Python

String Palindrome Program in Python

advertisement
advertisement
Method 1: Palindrome Program in Python using While Loop

In this method, we check for Palindrome number using while loop.

Program/Source Code

Here is source code of the Python Program to check whether a given number is a palindrome. The program output is also shown below.

 
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
    dig=n%10
    rev=rev*10+dig
    n=n//10
if(temp==rev):
    print("The number is a palindrome!")
else:
    print("The number isn't a palindrome!")
Program Explanation

1. The program works by first creating a variable called reversed_number and initializing it to 0.
2. Then, it uses a while loop to iterate over the digits of the number, starting from the least significant digit.
3. For each digit, the program adds it to the reversed_number variable and divides the number by 10 to get the next digit.
4. The while loop terminates when the value of the number is 0. This is because the least significant digit of a number is always 0, so once we reach the least significant digit, we know that we have reversed the entire number.
5. After the while loop terminates, the program compares the reversed_number variable to the original number.
6. If they are the same, then the number is a palindrome and the program returns True. Otherwise, the program returns False.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Time Complexity: O(log n)
The time complexity of the program is O(log n) as it depends on the number of digits in the input.

Space Complexity: O(1)
The space complexity of this program is O(1) because it uses a constant amount of extra space to store the variables ‘temp’, ‘rev’, and ‘dig’.

Runtime Test Cases

Testcase 1: In this case, we enter the number “121” as input to check whether it is a palindrome number or not.

Enter number:121
The number is a palindrome!

Testcase 2: In this case, we enter the number “567” as input to check whether the entered number is palindrome number or not.

advertisement
Enter number:567
The number isn't a palindrome!

Method 2: Palindrome in Python using Built-in Function

In this method, we use the built-in reversed() function. The reversed() function takes an iterable (e.g., a string, a list, or a tuple) and returns a reversed iterator.

Program/Source Code

Here is source code of the Python Program to check whether a given number is a palindrome or not using Built-in Function.

# Palindrome Program in Python using Built-in Function
 
def is_palindrome(n):
    return str(n) == ''.join(reversed(str(n)))
 
# Get the number from the user
n = int(input("Enter number: "))
 
# Check if the number is a palindrome
if is_palindrome(n):
  print("The number is a palindrome!")
else:
  print("The number is not a palindrome.")
Program Explanation

1. The user is prompted to enter a number.
2. The number is converted to a string.
3. The reversed() function is used to reverse the string.
4. The reversed string is compared to the original string.
5. If the reversed string is equal to the original string, then the number is a palindrome and the program prints “The number is a palindrome!”.
6. Otherwise, the number is not a palindrome and the program prints “The number is not a palindrome.”.

advertisement

Time complexity: O(n)
The time complexity of the program is O(n), where n is the number of digits in the number. This is because the str() function takes O(n) time to convert the number to a string, the reversed() function takes O(n) time to reverse the string, and the ”.join() function takes O(n) time to concatenate the strings.

Space complexity: O(1)
The space complexity of the program is O(1), because it only uses a constant amount of extra space to store the variables n, str(n), and ”.join(reversed(str(n))).

Program Output:

In this case, we enter the number “12321” as input to check whether it is a palindrome number or not.

Enter number:12321
The number is a palindrome!

Method 3: Palindrome in Python using Recursion

In this method, we use the built-in reversed() function. The reversed() function takes an iterable (e.g., a string, a list, or a tuple) and returns a reversed iterator.

Program/Source Code

Here is source code of the Python Program to check whether a given number is a palindrome or not using Recursion.

def is_palindrome(n, temp, rev=0):
    if n == 0:
        if temp == rev:
            return "The number is a palindrome!"
        else:
            return "The number isn't a palindrome!"
    else:
        dig = n % 10
        rev = rev * 10 + dig
        n = n // 10
        return is_palindrome(n, temp, rev)
 
n = int(input("Enter number:"))
result = is_palindrome(n, n)
print(result)
Program Explanation

1. The program begins by defining a function is_palindrome that checks whether a given number is a palindrome using recursion.
2. The function takes three parameters: n (the number being checked), temp (the original number), and rev (the reversed number). It also has a base case to handle when n becomes 0.
3. In the base case, it checks whether the reversed number (rev) is equal to the original number (temp) and returns the appropriate message.
4. If the base case is not met, the function proceeds with the recursion. It extracts the last digit (dig) of the number, updates the reversed number (rev), and removes the last digit from n. The function is then recursively called with the updated values.
5. The program prompts the user to enter a number and stores it in the variable n.
6. The is_palindrome function is called with the user’s input, and the result is stored in the variable result.
7. The program prints the result, indicating whether the input number is a palindrome or not.

Time Complexity: O(log10(n))
The program has a time complexity of O(log10(n)) because it processes each digit of the input number once, and the number of digits is approximately log10(n).

Space Complexity: O(log10(n))
The space complexity is also O(log10(n)) since the recursion depth and stack memory usage depend on the number of digits in the input.

Runtime Test Cases

Testcase 1: In this case, we enter the number “545” as input to check whether it is a palindrome number or not.

Enter number:545
The number is a palindrome!

Testcase 2: In this case, we enter the number “678” as input to check whether the entered number is palindrome number or not.

Enter number:678
The number isn't a palindrome!

Method 4: Palindrome in Python using Slicing

In this method, the program uses slicing to reverse the number’s digits and then compares it with the original number to check for palindromic properties.

Program/Source Code

Here is source code of the Python Program to check whether a given number is a palindrome or not using Slicing.

def is_palindrome(n):
    # Convert the number to a string
    num_str = str(n)
 
    # Use slicing to reverse the string
    reversed_str = num_str[::-1]
 
    # Compare the original string with the reversed string
    return num_str == reversed_str
 
n = int(input("Enter a number:"))
 
if is_palindrome(n):
    print("The number is a palindrome!")
else:
    print("The number is not a palindrome.")
Program Explanation

1. The program begins by defining a function, is_palindrome(n), which takes an integer n as its input.
2. Inside the function, it converts the integer n to a string using str(n).
3. Using string slicing with [::-1], it reverses the string, creating a new string called reversed_str.
4. The program then compares the original string num_str with the reversed string reversed_str to determine if the number is a palindrome.
5. If the strings are equal, it returns True, indicating that the number is a palindrome. Otherwise, it returns False.

Time Complexity: O(N)
The time complexity of this program is O(N), where N is the number of digits in the input number n. String slicing and string comparisons both have linear time complexity.

Space Complexity: O(N)
The space complexity is also linear and depends on the input’s size, used mainly for storing the reversed string reversed_str.

Program Output:

In this case, we enter the number “1368631” as input to check whether it is a palindrome number or not.

Enter number:1368631
The number is a palindrome!

To practice programs on every topic in Python, please visit “Programming Examples in Python”.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.