简体   繁体   English

使用python项目Euler#4。 我的代码有什么问题?

[英]Project Euler #4 with python. What;s wrong with my code?

I am trying to do project euler problem 4 using python. 我正在尝试使用python做项目Euler问题4。 The problem statement goes like this: 问题陈述如下:

A palindromic number reads the same both ways. 回文数在两个方向上都相同。 The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. 由两个两位数的乘积构成的最大回文数为9009 = 91×99。

Find the largest palindrome made from the product of two 3-digit numbers. 查找由两个3位数字的乘积组成的最大回文。

I wrote down a solution for it: 我为此写下了一个解决方案:

s=0
x=100
y=100
list=[]
z=x*y
def palindrome():
    while z>=1:
        s=s*10+z%10
        z=z/10
        if z==s:
            list.append(z)
while x<=999:
    while y<=999:
        palindrome()
        y=y+1
    x=x+1
    y=100
print list

It ended up giving an error along the lines of 'z referenced beyond assignment'. 最终按照“超出分配的z引用”的方式给出了错误。

I searched for a solution to this error before finally deciding to use the syntax 'global' to bypass this error. 在最终决定使用语法“ global”绕过此错误之前,我搜索了此错误的解决方案。

s=0
x=100
y=100
list=[]
z=x*y
def palindrome():
    global z
    global s
    global x
    global y
    global list
    while z>=1:
        s=s*10+z%10
        z=z/10
        if z==s:
            list.append(z)
while x<=999:
    while y<=999:
        palindrome()
        y=y+1
    x=x+1
    y=100
print list

Now it doesn't give an error, but it gives an empty list as output. 现在它没有给出错误,但是给出了一个空列表作为输出。 I tried to debug the code by inserting print statements in between. 我试图通过在两者之间插入打印语句来调试代码。 The loops appear to work fine, as 'x' and 'y' print all the values they are supposed to. 循环似乎可以正常工作,因为“ x”和“ y”会打印出所有应有的值。 However, I get an empty list as an output to the print list command and 'z' does not apparently change values and is stuck at 100000 despite me using while loops to change the values of x and y. 但是,我得到一个空列表作为打印列表命令的输出,尽管我使用了while循环来更改x和y的值,但是'z'显然没有改变值并且卡在100000。

I am at a loss on how to proceed from here. 我不知道如何从这里开始。

The error you got was probably: 您得到的错误可能是:

UnboundLocalError: local variable 'z' referenced before assignment

This means that z was not defined, at least not within the palindrome() function. 这意味着z没有定义,至少不在palindrome()函数中。 Your solution of adding the global keyword is technically correct. 您添加global关键字的解决方案在技术上是正确的。 However, as others have pointed out already, use of globals makes the code hard to follow. 但是,正如其他人已经指出的那样,使用全局变量会使代码难以遵循。

It's not clear to me what palindrome() is supposed to do. 我不清楚palindrome()应该做什么。 Is it supposed to check if a number is a palindrome? 是否应该检查数字是否是回文? Generate palindrome numbers? 生成回文数? To fix this problem, you should think about structuring your code. 要解决此问题,您应该考虑结构化代码。 There are many ways to do this, of course, and with time you will find your own style. 当然,有很多方法可以做到,随着时间的流逝,您将找到自己的风格。

My advice, then, is to think about how you would solve this in general. 因此,我的建议是考虑您一般如何解决此问题。 If you don't know the solution, coding won't help you. 如果您不知道解决方案,那么编码将无济于事。 Sometimes, when solving problems like this one, I write functions without declaring their bodies. 有时,在解决此类问题时,我在编写函数时不声明其主体。 You can do this top-down or bottom-up, both work. 您可以自上而下或自下而上地完成这两项工作。 For example: 例如:

def is_palindrome(n):
    """ Check if n is a palindrome number. """
    pass

def multiples_of_3_digits():
    """ Return all numbers that are the product of two 3-digit numbers ."""
    pass

def main():
    print max(n for n in multiples_of_3_digits() if is_palindrome(n))

This way you can focus on solving the problem, then on the actual coding. 这样,您可以专注于解决问题,然后专注于实际编码。 Maybe you will add helper functions or realize you can solve the problem in a more efficient way, but it's a start. 也许您将添加帮助程序功能或意识到可以以更有效的方式解决问题,但这只是一个开始。 Good luck! 祝好运!

min=100
max=999
max_palindrome = 0
for a in range(min,max + 1):
    for b in range(a + 1, max + 1):
        prod = a*b
        if prod > max_palindrome and str(prod)==(str(prod)[::-1]):
            max_palindrome = prod
print max_palindrome

Here we are only concerned with the maximum palindrome, and so we don't spend any time storing other palindromes once they are known to be non-maximum. 在这里,我们仅关注最大回文,因此,一旦已知其他回文数不是最大,我们就不会花费任何时间来存储它们。 Also, the if statement first checks if the given product is larger than the maximum known palindrome before using the string cast and list slice to check whether or not the number is even a palindrome. 同样,if语句首先使用字符串强制转换和列表切片检查给定产品是否大于最大已知回文数,然后检查该数字是否甚至是回文数。 This should speed up our code a bit since the greater than comparison will often fail, regardless of whether the product in question is a palindrome. 这将加快我们的代码的速度,因为无论所讨论的产品是否是回文,大于比较通常都会失败。 When we run this, we get the following. 当我们运行它时,我们得到以下内容。

906609

Alternate Way: 替代方式:

I would discourage you to use the global variables because of the reasons pointed out by others. 由于其他人指出的原因,我不鼓励您使用全局变量。 I would also like you to refer to Andre's approach as it will teach you to organize yourself. 我也希望您参考安德烈的方法,因为它会教您如何组织自己。 In this approach too I will be using 2 functions is_palindrome(num) [to check if the number is palindrome or not] and find_max_palindrome [to find the largest palindrome] 在这种方法中,我也将使用2个函数is_palindrome(num)[检查数字是否为回文数]和find_max_palindrome [查找最大的回文数]

def is_palindrome(num):
    reversed = 0
    original = num

    if num < 10:
        return True
    if num % 10 == 0:
        return False

    while num >= 1:
        reversed = (reversed * 10) + (num % 10)
        num = num/10

    if original == reversed:
        return True
    else:
        return False

def find_max_palindrome():
    max_palindrome = 0
    a = 999
    b = 999
    prod = 0

    while a > 99:
        b = 999
        while b >= a:
            prod = a*b
            if prod > max_palindrome and is_palindrome(prod):
                max_palindrome = prod
            b = b -1
        a = a - 1

    return max_palindrome

print find_max_palindrome()

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

相关问题 问题97-Euler项目:我的代码有什么问题? - Problem 97 - Project Euler : What's wrong with my code? 我对Project Euler#12的python解决方案出了什么问题? - What's wrong with my python solution to Project Euler #12? Project Euler #8 Python,我看不出代码有什么问题 - Project Euler #8 Python, I don't see what's wrong with the code 我对Euler 17项目的解决方案出了什么问题? - What's wrong with my solution to Project Euler 17? Euler#12,我的Python程序出了什么问题? - Euler#12, what's wrong with my Python program? 我的代码有什么问题? Python。 尝试制作游戏列表游戏 - What is wrong with my code? Python. Trying to make a gamelist game Project Euler 71的逻辑有什么问题? - What is wrong with my logic for Project Euler 71? Python-Euler项目#35-这种方法有什么问题? - Python - Project Euler #35 — what is wrong with this approach? 我的 Euler 项目代码有什么问题,它引发了不支持的操作数类型错误 - What is wrong with my code for project Euler which throws an unsupported operand type error 对于 euler 4 号项目,我只是想知道我的代码有什么问题。 一直在敲我的大脑,我不知道怎么做,这是在 python - for project euler number 4 i am just wondering what is wrong with my code. have been knacking my brain and i do not know how, this is on python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM