Get a skill gap analysis, personalised roadmap, and AI-powered resume optimisation.
Introduction
In this article, we'll explore the concept of palindrome numbers and how to determine them in Python without using extra space. Palindromes are unique numbers that read the same forwards and backward. We'll focus on Python's efficient methods for identifying such numbers, highlighting space-efficient strategies suitable for various programming scenarios.
What is Palindrome?
A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward. In other words, it is a sequence of characters that is spelled the same way from left to right and right to left. Examples of palindromes include "racecar," "level," and "madam." Palindromes are often used in puzzles, word games, and cryptography.
What is a Palindrome Number in python?
A number that is unchanged when the number or digits are reversed is known as a palindrome number in Python. For example, the palindrome numbers are 131, 22, 515, 2332, and 84848. I hope now you have got an fair understanding of the Palindrome Number in Python.
Let's have a look at the Problem statement based on Palindrome number in Python.
Palindrome Algorithm
The algorithm to Check if a String is a Palindrome:
Initialize Pointers: Start with two pointers: one at the beginning (left) and one at the end (right) of the string.
Loop Until Pointers Meet: Repeat the following steps until the left pointer is greater than or equal to the right pointer.
Compare Characters: If the characters at the left and right pointers are not equal, return false (the string is not a palindrome).
Move Pointers: Increment the left pointer by 1. Decrement the right pointer by 1.
End of Loop: If the loop completes without finding any unequal characters, return true (the string is a palindrome).
Pseudocode
function isPalindrome(str):
left = 0
right = length(str) - 1
while left < right:
if str[left] != str[right]:
return false
left += 1
right -= 1
return true
Problem statement
A number is provided to us. Our objective is to determine whether the provided number is a palindrome or not.
Before we move to the code logic for finding Palindrome Number in Python, let’s understand through some examples of Palindrome numbers in Python.
Sample Examples
The below are some examples of Palindrome Number in Python .
Input: n = 1991991
Output: YES
Explanation:
Original: 1991991
After reversing: 1991991
The given number is the same as the reversed number formed by doing certain operations. This implies that the provided number is a palindrome number in python.
Input: 33568
Output: NO
Explanation:
Original: 33543
After reversing: 86533
The given number is not the same as the reversed number formed. This implies that the number is definitely not a palindrome number in python.
Now, Let’s move on to the code the logic for finding a Palindrome Number using Python.
Palindrome in Python Code
In this article, we explore four different ways to write a Palindrome Program in Python using slicing, loops, in-built functions, and recursion.
Method 1: Using While Loop (number)
Python
Python
num = 1001 temp = num reverse_num = 0 while temp != 0: digit = temp % 10 reverse_num = (reverse_num * 10) + digit temp //= 10 if num == reverse_num: print(num, "is a palindrome number") else: print(num, "is not a palindrome number")
You can also try this code with Online Python Compiler
In this code, we first take the input number from the user. We then create a temporary variable to store the number and a variable called reverse_num to store the reversed number. We use a while loop to extract the digits of the number one by one and build the reversed number by multiplying the current reverse_num by 10 and adding the current digit. Once the loop is done, we check if the original number is equal to the reversed number and print an appropriate message.
In this code, we first take the input string from the user and find its length. We then initialize two variables i and j to point to the first and last characters of the string, respectively. We use a while loop to compare the characters at the i and j indices of the string. If they don't match, we print a message saying that the string is not a palindrome and break out of the loop. If the loop completes without breaking, we print a message saying that the string is a palindrome.
Output
palap is a palindrome string
Method 3: Using String Slicing
Python
Python
def is_palindrome(number): # Step 1: Convert the number to a string num_str = str(number)
# Step 2: Reverse the string using slicing reversed_str = num_str[::-1]
# Step 3: Compare the original and reversed strings if num_str == reversed_str: return True else: return False # Example usage number = 12321 if is_palindrome(number): print(f"{number} is a palindrome number.") else: print(f"{number} is not a palindrome number.")
You can also try this code with Online Python Compiler
The provided Python code defines a function “is_palindrome” that checks if a given number is a palindrome. It first converts the number into a string, then reverses this string using Python's string slicing feature ([::-1]). Finally, it compares the original string with the reversed one. If both strings are identical, the number is a palindrome, and the function returns True; otherwise, it returns False. This method leverages Python's concise syntax for string manipulation, offering a straightforward and elegant solution to identify palindrome numbers.
Method 4: Using Character matching
Python
Python
def is_palindrome(number): # Convert the number to a string for character access num_str = str(number)
# Iterate from the start to the middle of the string for i in range(len(num_str) // 2): # Compare characters from the start and end if num_str[i] != num_str[len(num_str) - 1 - i]: # If any characters don't match, it's not a palindrome return False
# If all characters match, it's a palindrome return True # Example usage number = 12321 if is_palindrome(number): print(f"{number} is a palindrome number.") else: print(f"{number} is not a palindrome number.")
You can also try this code with Online Python Compiler
The provided Python code defines a function is_palindrome that checks whether a given number is a palindrome by utilizing character matching. It starts by converting the number into a string for easier character access. Then, it iteratively compares characters from the beginning and end of the string, moving towards the center. If any pair of corresponding characters don't match, the function immediately returns False, indicating the number is not a palindrome. If all pairs match, the function concludes the number is a palindrome and returns True. This method efficiently minimizes the number of comparisons needed, especially beneficial for long numbers, by checking only half of the string.
Method 5: Using for loop
To determine if a number is a palindrome, we can convert the number to a string and check if it reads the same forwards and backwards. Here's how you can implement this using a for loop:
Python
Python
def is_palindrome(number): # Convert number to string num_str = str(number)
# Iterate through half of the string for i in range(len(num_str) // 2): if num_str[i] != num_str[-(i + 1)]: return False return True
# Example usage: num1 = 121 num2 = 12321
print(f"{num1} is palindrome: {is_palindrome(num1)}") print(f"{num2} is palindrome: {is_palindrome(num2)}")
You can also try this code with Online Python Compiler
So, assuming input is provided in the string format or Type (Because if the number is greater than 10^18, then we have to store it in a String variable),
Run a loop from starting to length/2 and check the string's first and last characters, as well as the second and third ones, and so on. Any character mismatch would make the string a non-palindrome Number or string. Here the input is provided in string format
Python
Python
def isPalindrome(str): #Loop from index 0 to mid of the string. for i in range(0, len(str)//2): if str[i] != str[len(str)-i-1]: return False return True
# Driver code of function str = "33568"
if(checkPalindrome(str) == True): print("Yes, it is a palindrome!") else: print("No, it is not a palindrome!")
You can also try this code with Online Python Compiler
Time Complexity: O(|str|) As the for loop inside the function isPalindrome is iterating from 0 to mid of the str, in this case, we can say that the iteration is over n/2 digits, and that makes our complexity as O(|str|)
Space Complexity: O(1) As there is no extra space used by the program, Hence the space complexity is constant. Moving ahead to check another approach of the same time and space complexity.
Approach 2: Using the Reverse number
Assuming input is a number here, i.e., it is stored in int Format and not as string.
Run a loop from till the number doesn't get equal to Zero. In every iteration, Take the number %10 to get the Last digit, keep forming the reverse in the iteration, and later divide the number by ten so that number gets shorter. Here the input is not provided in string format.
Python
Python
n=1991991 temp=n rev=0
while(n>0): dig=n%10 rev=rev*10+dig n=n//10
if(temp==rev): print("Yes, the number is a palindrome!") else: print("No, the number isn't a palindrome!")
You can also try this code with Online Python Compiler
Time Complexity: O(n) Here n is the number of digits in the provided number.
Space Complexity: O(1) As there is no extra space used by the program, Hence the space complexity is constant. I hope now you understand the logic behind the Palindrome numbers program.
Approach 3: Using recursion
Python
Python
def is_palindrome(n): """ Returns True if n is a palindrome number, False otherwise. """ # Base case: one-digit numbers are always palindromes if n // 10 == 0: return True # Recursive case: compare first and last digits, then check the remaining digits first_digit = n % 10 last_digit = n // (10 ** (len(str(n)) - 1)) if first_digit != last_digit: return False else: # Remove the first and last digits from the number and check the remaining digits recursively return is_palindrome((n % (10 ** (len(str(n)) - 1))) // 10) # Example usage:
print(is_palindrome(12321)) # True
You can also try this code with Online Python Compiler
Time Complexity: O(n) Here n is the number of digits in the provided number.
Space Complexity: O(1) The space complexity of the above code is O(log n), where n is the input number.
This is because the recursive function is_palindrome() is called recursively for each pair of digits at the beginning and end of the input number. The depth of the recursion is equal to the number of digits in the input number, which is O(log n) in terms of the number of digits.
You can practice by yourself with the help of online python compiler for better understanding.
Frequently Asked Question
What is the condition for palindrome in Python?
A string is a palindrome in Python if it remains the same when reversed. This can be checked by comparing the original string with its reversed version using slicing syntax or the built-in reversed() function.
How do you check the number is palindrome or not?
To check if a number is a palindrome, convert it to a string and compare it with its reverse. In Python, this can be done with str(num) == str(num)[::-1]. If the original number and its reversed version are the same, the number is a palindrome.
Why do we use palindrome in Python?
We use palindromes in Python for a variety of purposes, such as data validation, string manipulation, and solving algorithmic problems. Palindromes help us validate input data, manipulate strings, and solve various problems involving palindromic sequences.
What is the fastest way to find palindrome in Python?
The fastest way of checking palindrome in Python is using indexing. We create a reversed copy of the string and then compare it with the string itself; if they both are the same, then we conclude that the string is, in fact, a palindrome.
How many loops required to check palindrome?
To check if a string is a palindrome, you only need to iterate over half of the characters in the string, which is approximately len(string) // 2 (rounded down) using a loop that compares the characters at opposite ends of the string.
Conclusion
This article thoroughly explored how to identify palindrome numbers in Python. We delved into the definition of palindromes and examined Python's succinct and efficient approach to determining if a given number exhibits this symmetrical property without additional memory resources.