Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Palindrome in Python: How to check a number is palindrome?
A palindrome is a string that reads the same forwards and backwards. In other words, a palindrome string is equal to its reverse.
For example, "civic" and "madam" are palindromes, while "cat" is not (its reverse "tac" differs from the original).
Method 1: Using String Slicing
The simplest approach is to reverse the string using slicing and compare it with the original ?
def isPalindrome(s):
rev = s[::-1]
if rev == s:
return True
return False
text = "madam"
print(f"'{text}' is palindrome:", isPalindrome(text))
text = "hello"
print(f"'{text}' is palindrome:", isPalindrome(text))
'madam' is palindrome: True 'hello' is palindrome: False
Method 2: Using Two Pointers
This approach compares characters from both ends moving inward, without creating a reversed string ?
def isPalindrome(s):
start = 0
end = len(s) - 1
while start < end:
if s[start] != s[end]:
return False
start += 1
end -= 1
return True
text = "madam"
print(f"'{text}' is palindrome:", isPalindrome(text))
text = "reader"
print(f"'{text}' is palindrome:", isPalindrome(text))
'madam' is palindrome: True 'reader' is palindrome: False
Method 3: Checking Numeric Palindromes
For numbers, convert to string first or use mathematical operations ?
def isNumericPalindrome(num):
# Convert to string and check
return str(num) == str(num)[::-1]
def isNumericPalindromeByMath(num):
# Using mathematical approach
original = num
reversed_num = 0
while num > 0:
reversed_num = reversed_num * 10 + num % 10
num //= 10
return original == reversed_num
number = 12321
print(f"{number} is palindrome:", isNumericPalindrome(number))
number = 12345
print(f"{number} is palindrome:", isNumericPalindromeByMath(number))
12321 is palindrome: True 12345 is palindrome: False
Comparison
| Method | Space Complexity | Best For |
|---|---|---|
| String Slicing | O(n) | Simple, readable code |
| Two Pointers | O(1) | Memory-efficient |
| Mathematical | O(1) | Numeric palindromes |
Conclusion
Use string slicing for simplicity, two pointers for memory efficiency, and mathematical approach for numeric palindromes. The two-pointer method is most optimal for large strings.
Advertisements
