为什么这个简单的 Python 脚本会显示错误的答案?

发布于 2024-09-07 18:25:13 字数 576 浏览 1 评论 0原文

我再次致力于欧拉计划,这次是问题 #4。该脚本的要点是找到两个三位数的最大回文积。我认为解决起来相当简单,但我得到的答案太低了。更具体地说,我得到 580085,答案是 906609。

有人能告诉我这个错误是什么吗?

#!/usr/bin/env python
# encoding: utf-8
"""
P4.py

Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""

import sys
import os


def main():
    for x in range(100, 1000):
        for y in range(100, 1000):
            z = str( x * y )
            s = str( z[::-1] ) # Reverse z
            if z == s:
                t = z
    print t


if __name__ == '__main__':
    main()

I'm again working on Project Euler, this time problem #4. The point of this script is to find the largest palindromic product of two three digit numbers. I thought it was fairly straightforward to solve, but I'm getting an answer that is too low. More specifically, I am getting 580085, and the answer is 906609.

Could someone tell me what about this is incorrect?

#!/usr/bin/env python
# encoding: utf-8
"""
P4.py

Created by Andrew Levenson on 2010-06-29.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""

import sys
import os


def main():
    for x in range(100, 1000):
        for y in range(100, 1000):
            z = str( x * y )
            s = str( z[::-1] ) # Reverse z
            if z == s:
                t = z
    print t


if __name__ == '__main__':
    main()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小猫一只 2024-09-14 18:25:13

您的代码不能确保它打印最大的产品,因为稍后可能会有更小的产品取代它。要修复此问题,请将 t 初始化为零,并将条件替换为

if z==s and int(z)>t:
    t = int(z)

或者等效地,

if z==s:
    t = max(t,int(z))

编辑:修复了上面的 int/string 问题。不过,避免像这样转换为 string 并返回 int 会更干净一些:

def isPalindrome(x):
    s = str(x)
    return s == s[::-1]

t = 0
for x in range(100, 1000):
    for y in range(100, 1000):
        z = x * y
        if isPalindrome(z) and z > t:
            t = z
print t

Your code doesn't make sure it prints the largest product, since there could later be a smaller product which replaces it. To fix it, initialize t to zero, and replace your condition with

if z==s and int(z)>t:
    t = int(z)

Or equivalently,

if z==s:
    t = max(t,int(z))

Edit: Fixed int/string issues above. It's a bit cleaner to avoid the conversion to string and back to int like this though:

def isPalindrome(x):
    s = str(x)
    return s == s[::-1]

t = 0
for x in range(100, 1000):
    for y in range(100, 1000):
        z = x * y
        if isPalindrome(z) and z > t:
            t = z
print t
深居我梦 2024-09-14 18:25:13

这是在单个表达式中执行此操作的一种棘手但正确的方法...:

def main():
  print max(p for x in range(100, 1000) for y in range(x, 1000)
              for p in (x * y,) if str(p) == str(p)[::-1])

棘手的部分是单项 for p 子句,它起着赋值的作用(只是为了停止重新计算该乘积)次;-)。

请注意,接受的答案是错误的(与其他几个答案一样),因为它查找字符串“max”,这与int max不同 - 尝试运行它,你就会看到!-)

Here's a tricky but correct way to do it in a single expression...:

def main():
  print max(p for x in range(100, 1000) for y in range(x, 1000)
              for p in (x * y,) if str(p) == str(p)[::-1])

The tricky part is the single-item for p clause which plays the role of an assignment (just to stop recomputing that product several times;-).

Note that the accepted answer is wrong (as are several others), because it looks for the string "max", which is different from the int max -- try running it, and you'll see!-)

等风也等你 2024-09-14 18:25:13

问题是找到最大的回文数。你在这里找不到最大的,只能找到最后一个。您假设最后一个是最大的,但事实并非如此,因为您正在检查整个 ZxZ 可能性的平方。

例如,在考虑了 101*999 之后,您正在考虑 200*101。

The problem is to find the largest palindrome. You have nothing here to find the largest, simply the last. You assumed the last one would be the largest, but that isn't so because you are examining the entire ZxZ square of possibilities.

For example, you are considering 200*101 after you've considered 101*999.

请止步禁区 2024-09-14 18:25:13

由于您使用 2 个 for 循环的方式,您将获得具有最大 x 值的数字,而不是最大的乘积。

906609 = 993 * 913

然后 x 不断递增,下一个回文是:

580085 = 995 * 583

您需要一个变量来跟踪您找到的最大回文。

def main():
    largest = 0
    for x in range(100, 1000):
        for y in range(100, 1000):
            z = str( x * y )
            s = str( z[::-1] ) # Reverse z
            if z == s:
                t = int(z)
                if t > largest:
                    largest = t
    print largest

Because of the way you're using the 2 for loops you're going to get the number with the largest x value, not the largest product.

906609 = 993 * 913

Then x keeps incrementing and the next palindrome is:

580085 = 995 * 583

You need a variable to keep track of the largest palindrome you've found.

def main():
    largest = 0
    for x in range(100, 1000):
        for y in range(100, 1000):
            z = str( x * y )
            s = str( z[::-1] ) # Reverse z
            if z == s:
                t = int(z)
                if t > largest:
                    largest = t
    print largest
〗斷ホ乔殘χμё〖 2024-09-14 18:25:13

如果您找到的支票比您已有的支票大,则需要添加一张支票。

You need to add a check if the one you found is larger than the one you already have.

○愚か者の日 2024-09-14 18:25:13

我要补充一点,你可以在这个测试中节省一些时间。所有 6 位回文数必须能被 11 整除。因此,至少有一个因数必须能被 11 整除。

I'll add that you can save yourself some time in this test. All 6 digit palindromes must be divisible by 11. Therefore at least one of the factors must be divisible by 11.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文