Check if a Number is a Palindrome in Python
A palindrome is a number (or a word, phrase, etc.) that reads the same backward as forward. For instance, numbers like 121, 1331, and 989 are palindromes because reversing them gives the same result. In Python, checking if a number is a palindrome is a simple task. This blog will guide you through various methods to determine whether a given number is a palindrome.
What Is a Palindrome?
A number is said to be a palindrome if it remains the same when its digits are reversed. For example:
- 121 β Reversed: 121 (Palindrome β )
- 123 β Reversed: 321 (Not a Palindrome β)
- 1331 β Reversed: 1331 (Palindrome β )
Method 1: Converting the Number to a String
One of the easiest ways to check if a number is a palindrome is by converting the number to a string, reversing the string, and comparing it with the original string.
Code Example:
# Program to check if a number is a palindrome by converting to a string
# Step 1: Define a function to check if the number is a palindrome
def is_palindrome(n):
# Convert the number to a string
original = str(n)
# Reverse the string
reversed_num = original[::-1]
# Step 2: Check if the original string is equal to the reversed string
return original == reversed_num
# Step 3: Test the function
number = 121
if is_palindrome(number):
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
Explanation:
- String Conversion: We convert the number to a string using
str()
. - Reversing the String: The string slicing technique
[::-1]
is used to reverse the string. - Comparison: We compare the original string with the reversed string. If they are equal, the number is a palindrome.
- Output: The result is printed based on the comparison.
Output:
121 is a palindrome
Method 2: Using Mathematical Operations (Without Converting to String)
If you want to check if a number is a palindrome without converting it to a string, you can use mathematical operations to reverse the digits and compare them.
Code Example:
# Program to check if a number is a palindrome using mathematical operations
# Step 1: Define a function to reverse the number
def is_palindrome(n):
original = n
reversed_num = 0
# Step 2: Reverse the digits of the number
while n > 0:
digit = n % 10 # Get the last digit
reversed_num = reversed_num * 10 + digit # Append the digit to the reversed number
n = n // 10 # Remove the last digit from the original number
# Step 3: Check if the reversed number is equal to the original number
return original == reversed_num
# Step 4: Test the function
number = 1331
if is_palindrome(number):
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
Explanation:
- Digit Extraction: We use the modulo operator (
%
) to extract the last digit of the number. - Reversing the Number: We build the reversed number by appending each extracted digit to
reversed_num
. - Removing Digits: After extracting each digit, we divide the number by 10 to remove the last digit.
- Comparison: We compare the original number with the reversed number. If they match, the number is a palindrome.
- Output: The result is printed based on the comparison.
Output:
1331 is a palindrome
Method 3: Checking Palindrome Using Recursion
Recursion is another way to check if a number is a palindrome, although itβs less efficient than the previous methods. We can recursively break down the problem and check the first and last digits of the number.
Code Example:
# Program to check if a number is a palindrome using recursion
# Step 1: Define a recursive function to check palindrome
def is_palindrome_recursive(n, rev=0):
if n == 0:
return rev
rev = rev * 10 + n % 10 # Reverse the number step by step
return is_palindrome_recursive(n // 10, rev)
# Step 2: Test the function
number = 1221
if number == is_palindrome_recursive(number):
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
Explanation:
- Recursive Function: The function
is_palindrome_recursive()
reverses the number step by step. - Base Case: When the number reaches zero, the reversed number is returned.
- Recursive Call: We recursively append each last digit to
rev
and reduce the number. - Comparison: The final reversed number is compared with the original number to check if it is a palindrome.
Output:
1221 is a palindrome
Method 4: Using List Comparison
If you like working with lists, you can convert the digits of the number into a list and compare it with the reversed list.
Code Example:
# Program to check if a number is a palindrome using list comparison
# Step 1: Define a function to check palindrome using list comparison
def is_palindrome(n):
# Convert the number into a list of digits
digits = list(str(n))
# Step 2: Compare the list with its reversed version
return digits == digits[::-1]
# Step 3: Test the function
number = 989
if is_palindrome(number):
print(f"{number} is a palindrome")
else:
print(f"{number} is not a palindrome")
Explanation:
- List Conversion: We convert the number into a list of digits by first converting it to a string, and then using
list()
. - Comparison: We compare the original list of digits with the reversed version of the list.
- Output: The result is printed based on the comparison.
Output:
989 is a palindrome
Conclusion
In this blog, we covered several methods to check if a number is a palindrome in Python:
- String Conversion: Convert the number to a string and compare it with its reverse.
- Mathematical Operations: Reverse the number using arithmetic and compare the original and reversed numbers.
- Recursion: Use recursive function calls to reverse the number and check if it’s a palindrome.
- List Comparison: Convert the number into a list of digits and compare it with the reversed list.
Each method has its own advantages and trade-offs. Choose the one that best suits your needs! Keep practicing, and you’ll master these techniques in no time.
Stay tuned for more Python tutorials! π