Python程序查找指定范围内所有奇数回文数
当需要查找所有为奇数且为回文数,并且位于给定值范围内的数字,并且已告知不能使用递归时,可以使用列表推导式和“%”运算符来实现相同的功能。
回文是指从左到右读和从右到左读都相同的字符串。
以下是演示示例:
示例
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)
输出
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]
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
解释
- 定义一个空列表、一个下限和一个上限。
- 在控制台上显示上限和下限。
- 迭代上限和下限之间的值,并检查它是否能被2整除。
- 然后,将其转换为字符串,并比较字符串的末尾元素和字符串本身。
- 将其赋值给一个变量。
- 在控制台上显示输出。
广告