Skip to main content
 首页 » 编程设计

python之为什么 str(a) == reversed(str(a)) 在 Python 中不能用作回文测试

2025年05月04日33mfrbuaa

我一直试图在 Python 欧拉项目中找到问题 #4 的答案,但我似乎真的无法在我的代码中找到问题。这是问题:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

这是我的代码:

nums = list(range(10000, 998001)) 
 
pals = [] 
def palindrome(a): 
    if str(a) == reversed(str(a)): 
        pals.append(a) 
 
for every in nums: 
    palindrome(every) 

请您参考如下方法:

首先,尝试打印出字符串及其假设的反转 - 您会发现它们并不像您预期​​的那样。获得 s 字符串反转的更明智的方法是使用 s[::-1]。

然后你需要意识到你正在检查你的那个范围内的每个数字,10000..998000(注意我遗漏了998001 因为 Python 范围在末尾是独有的)。并非所有这些数字都是两个 3 位数的乘积。当然,这可能是您获得所有回文后的下一步,在这种情况下,您可以随意忽略这一段(当然除了固定范围之外)。


顺便说一句,我可能不会将该范围包含在列表中。如果您使用的是 Python 2,它已经是一个列表,对于 Python 3,最好将其保留为惰性迭代器以免浪费内存。


最后,我可能不会这样做,因为我更喜欢可读代码,但那些需要“Pythonic”解决方案的人可能喜欢看类似的东西:

print(max((i*j 
    for i in range(100,1000) 
    for j in range(100,1000) 
    if str(i*j) == str(i*j)[::-1] 
    ))) 

当然 true Python 爱好者会希望它在一行中 :-) 为了便于阅读,我只是将其拆分。