簡體   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