1

我正在做项目欧拉问题,以帮助我理解这里有人建议的算法背后的数学。我不想要代码,我只想朝着正确的方向推动以找出我哪里出错了。

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
4

1 回答 1

1

您在同一个循环中递减stopj,因此您只生成正方形999*999998*998997*997等。在不进一步研究您的代码的情况下,我认为您想要的是将stop常量保留在 中genThreeValues,而是使用具有多个值的生成器stop

于 2013-10-12T16:14:19.817 回答