- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Find All Numbers which are Odd and Palindromes Between a Range of Numbers
When it is required to find all the numbers that are odd, and are palindromes and lie between a given range of values, and it has been told that recursion can’t be used, then, list comprehension, and ‘%’ operator can be used to achieve the same.
Palindromes are string that are same when they are read in either way- left to right and right to left.
Below is a demonstration for the same −
Example
my_list = [] lower_limit = 5 upper_limit = 189 print("The lower limit is : ") print(lower_limit) print("The upper limit is : ") print(upper_limit) my_list = [x for x in range(lower_limit,upper_limit+1) if x%2!=0 and str(x)==str(x)[::-1]] print("The numbers which are odd and palindromes between " + str(lower_limit) + " and " + str(upper_limit) + " are : ") print(my_list)
Output
The lower limit is : 5 The upper limit is : 189 The numbers which are odd and palindromes between 5 and 189 are : [5, 7, 9, 11, 33, 55, 77, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181]
Explanation
- An empty list, a lower limit and an upper limit is defined.
- The upper and lower limit are displayed on the console.
- The values between upper and lower limit are iterated over, and checked to see if it is divisible by 2.
- Then, it is converted to a string, and elements from the end of the string and the string are compared.
- This is assigned to a variable.
- This is displayed as output on the console.
Advertisements