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
Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
When it is required to find all numbers that are odd and palindromes within a given range, list comprehension and the modulo operator (%) can be used to achieve this efficiently.
A palindrome is a number that reads the same forwards and backwards, such as 121 or 1331. For a number to be both odd and a palindrome, it must satisfy two conditions: divisibility check and string comparison.
Syntax
result = [x for x in range(start, end+1) if x%2!=0 and str(x)==str(x)[::-1]]
Example
Here's how to find all odd palindromes in a given range ?
# Define the range
lower_limit = 5
upper_limit = 189
print("The lower limit is:", lower_limit)
print("The upper limit is:", upper_limit)
# Find odd palindromes using list comprehension
odd_palindromes = [x for x in range(lower_limit, upper_limit+1)
if x % 2 != 0 and str(x) == str(x)[::-1]]
print(f"Odd palindromes between {lower_limit} and {upper_limit}:")
print(odd_palindromes)
The lower limit is: 5 The upper limit is: 189 Odd palindromes between 5 and 189: [5, 7, 9, 11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181]
How It Works
The list comprehension performs two checks for each number in the range:
-
Odd check:
x % 2 != 0ensures the number is odd -
Palindrome check:
str(x) == str(x)[::-1]compares the number with its reverse
Alternative Approach Using Functions
For better code organization, you can create separate functions ?
def is_palindrome(num):
"""Check if a number is a palindrome"""
return str(num) == str(num)[::-1]
def is_odd(num):
"""Check if a number is odd"""
return num % 2 != 0
def find_odd_palindromes(start, end):
"""Find all odd palindromes in a range"""
return [x for x in range(start, end+1) if is_odd(x) and is_palindrome(x)]
# Test the function
result = find_odd_palindromes(10, 200)
print("Odd palindromes between 10 and 200:")
print(result)
Odd palindromes between 10 and 200: [11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]
Key Points
- List comprehension provides a concise way to filter numbers based on multiple conditions
- String slicing with
[::-1]reverses the string representation of the number - The modulo operator
%efficiently checks for odd numbers - Both single−digit and multi−digit palindromes are handled automatically
Conclusion
Using list comprehension with modulo and string reversal operations provides an efficient solution to find odd palindromes. This approach is both readable and performant for reasonable ranges of numbers.
---