Python中的回文不起作用

时间:2014-03-27 20:48:25

标签: python-3.x palindrome

我正在尝试制作一个简单的程序,在Python3中显示2个数字之间的回文数,但它似乎不起作用。我得到的只有4个输出,分别是1,2,4和8.其他数字如11,22,33,......,111,121,131,......,191,222等等呢?

这是我的代码。我无法弄清楚它为什么不起作用。

a = 0
b = 500
a += 1
for i in range(a,b):
    if(str(a) == str(a)[::-1]):
        print(a)
        a += a

2 个答案:

答案 0 :(得分:2)

也许

for i in range (0, 500):
    if str(i) == str(i)[::-1]:
        print(i)

答案 1 :(得分:1)

>>> palindromes = [a for a in range(500) if str(a) == str(a)[::-1]]
>>> palindromes
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131,
 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 
 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474,
 484, 494]

这显示了你的原则。如果你想在一个函数中做到这一点,你可以使用yield而不是在内存中构建整个列表(效率更高):

>>> def palindromes(a, b):                                                  
...   """Return palindromes in closed interval from a to b"""               
...   for i in range(a, b):                                                 
...     if str(i) == str(i)[::-1]:                                          
...       yield i                                                           
...                                                                         
>>> list(palindromes(0, 500))                                               
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242, 252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383, 393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494]