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

Python 从两个3位数字的乘积得到最大回文,我的计算哪里会出错?,python,combinations,Python,Combinations,我正在做Euler问题项目,以帮助我理解这里有人建议的算法背后的数学。 我不想要代码,我只想朝正确的方向推动,找出我的错误所在 def genYieldThreeValues(stop): j = 999 while stop >99 and j > 99: multiples = str(stop * j) front = multiples[:3] # get front three numbers back =

我正在做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))
(编辑:新代码)


在同一个循环中,你同时递减
stop
j
,这样你就只生成了
999*999
998*998
997*997
,等等。在不进一步研究你的代码的情况下,我认为你想要的是在
genThreeValues
中保持
stop
常量,相反,使用具有多个值
stop
的生成器,您在同一循环中同时递减
stop
j
,这样您只生成正方形
999*999
998*998
997*997
,等等,而无需进一步研究您的代码,我想你想要的是让
stop
genThreeValues
中保持不变,而是使用具有多个
stop

值的生成器谢谢,切普纳,我最终得到了正确的答案,但不是非常优雅或高效的方式。我会好好考虑一下,明天再努力提高。再次感谢。添加了工作代码,你能给我一些如何提高效率的建议吗?大约需要700毫秒才能返回正确的值谢谢,切普纳,我最终得到了正确的答案,但不是以一种非常优雅或高效的方式。我会好好考虑一下,明天再努力提高。再次感谢。添加了工作代码,你能给我一些如何提高效率的建议吗?返回正确的值大约需要700毫秒
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