繁体   English   中英

在我的计算中,要从两个3位数的乘积中得到最大的回文数,在哪里出错?

[英]where am I going going wrong in my calculations to get largest palindrome made from the product of two 3-digit numbers?

我正在做项目Euler问题,以帮助我理解此处有人建议的算法背后的数学。 我不想要代码,而只是想朝着正确的方向来找出我要去哪里的地方。

def genYieldThreeValues(stop):

    j = 999
    while stop >99 and j > 99:
        multiples = str(stop * j)
        front = multiples[:3] # get front three numbers
        back = multiples[-3:] # get last three numbers
        stop-=1
        j-=1
        yield  [front,back,multiples] # yield a list with first three, last three and all numbers


def highestPalindrome(n):

    for x in genYieldThreeValues(n):
        if   x[1] ==x[0][::-1]: # compare first three and last three digits reversed
            return x[2]         # if they match return value

print(highestPalindrome(999))

(编辑:新代码)

def genYieldThreeValues(stop):
while stop >99:
    yield stop

def highestPalindrome(n):
highest = 0
for x in range(genYieldThreeValues(n).next(),99,-1):
    for i in range(x,99,-1):
        product = str(x*i)
        if product[::-1]  == product and product > highest:
            if len(product) > 5:
                highest = product
return highest

您正在递减都stopj在同一个循环,这样就只生成平方999*999998*998997*997 ,等等。没有进一步研究你的代码,我你想要的是离开stop在不断genThreeValues ,而是使用具有多个stop值的那个生成器。

暂无
暂无

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

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