简体   繁体   English

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

[英]Why doesn't str(a) == reversed(str(a)) work as a palindrome test in Python?

I have been trying to find the answer to problem #4 in Project Euler in Python but I really can´t seem to find the problem in my code. 我一直在尝试在Python的Euler项目中找到问题4的答案,但是我似乎在我的代码中似乎找不到问题。 Here is the question: 这是问题:

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. 由两个2位数字的乘积组成的最大回文为9009 = 91×99。找到由两个3位数字的乘积组成的最大的回文。

And here is my code: 这是我的代码:

nums = list(range(10000, 998001))

pals = []
def palindrome(a):
    if str(a) == reversed(str(a)):
        pals.append(a)

for every in nums:
    palindrome(every)

For a start, try printing out the string and its supposed reversal - you'll find they're not as you expect. 首先,请尝试打印出字符串及其假定的反转-您会发现它们不是您期望的那样。 A more sensible way of getting the string reversal of s is with s[::-1] . 获得s的字符串反转的更明智的方法是使用s[::-1]

Then you need to realise that you're checking every number in that range of yours, 10000..998000 (noticing I've left out 998001 there since Python ranges are exclusive at the end). 然后,你需要意识到你正在检查该范围内你的每一个数字, 10000..998000 (注意到我已经离开了998001有因为Python范围是独家末)。 Not all of those numbers will be a product of two 3-digit numbers. 并非所有这些数字都是两个3位数字的乘积。 Of course, it may be that was going to be your next step once you'd got all the palindromes, in which case feel free to ignore this paragraph (other than fixing the range, of course). 当然,一旦您获得了所有回文,就可能是下一步,在这种情况下,可以忽略此段(当然,除了确定范围之外)。


As an aside, I probably wouldn't wrap that range in a list. 顺便说一句,我可能不会将该范围包装在列表中。 If you're using Python 2, it's already a list and, for Python 3, it's probably better to leave it as a lazy iterator so as not to waste memory. 如果您使用的是Python 2,则已经是列表,对于Python 3,最好将其保留为惰性迭代器,以免浪费内存。


And, as a final aside, I probably wouldn't do it this way since I prefer readable code but those who demand "Pythonic" solutions may like to look at something like: 而且,最后,我可能不会这样做,因为我更喜欢可读的代码,但是那些需要“ 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]
    )))

though of course true Python aficionados will want that on a single line :-) I've just split it for readability. 尽管当然, 真正的 Python爱好者会希望将其放在一行上:-)为了便于阅读,我将其拆分了。

Python's reversed returns an iterator object. Python的reversed iterator 返回一个iterator对象。 So, no one string could be equal to the iterator. 因此,没有一个字符串可以等于迭代器。

Because reversed returns an iterator object, you should replace str(a) == reversed(str(a)) with str(a) == str(a)[::-1] . 因为reversed返回一个iterator对象,所以您应将str(a) == reversed(str(a))替换为str(a) == str(a)[::-1] The [::-1] qualifier is a string splicing that will reverse the collection. [::-1]限定词是一个字符串拼接,它将使集合反向。

Let me start with what everyone else pointed out: reversed(s) is not the same as s[::-1] . 让我从其他所有人指出的内容开始: reversed(s)s[::-1]

Everyone else wanted you to use s[::-1] instead of reversed() . 其他人都希望您使用s[::-1]而不是reversed() Sure, that suggestion is scrutable and idiomatic. 当然,这个建议是可以理解的,是惯用的。 But why limit yourself! 但是为什么要限制自己! This is Python, after all. 毕竟是Python。

from itertools import combinations, ifilter, imap, starmap
from operator import eq, mul

def is_palindrome(integer):
    """Returns a True if an input integer's digits are palindromic, False otherwise."""
    string = str(integer) 
    return all(imap(eq, iter(string), reversed(string)))

def largest_palindrome_product(n_digits=3):
    """Solves Project Euler #4"""
    all_n_digit_numbers = xrange(10**(n_digits)-1, 10**(n_digits-1), -1)
    palindromes = ifilter(is_palindrome, 
                          (starmap(mul, combinations(all_n_digit_numbers, 2)))
                         )
    return max(palindromes)

largest_palindrome_product()

This solution has the valuable feature of retaining the use of reversed() ! 该解决方案具有保留使用reversed()的宝贵功能! For extra inscrutability I tried to use as many functions from itertools as I could. 为了获得更好的可操作性,我尝试使用itertools尽可能多的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM