簡體   English   中英

找出由兩個 2 位數字的乘積構成的最大回文

[英]To find the largest palindrome made from the product of two 2-digit numbers

def largest_palindrome(n1,n2):
    mylist = [x for x in range(n1,n2)]
    for y in mylist:
        if y == y[::-1]:
            print(y)
        else:
            pass    

large_palindrome(100,9801)

當我執行此代碼時,出現的錯誤是TypeError: 'int' object is not subscriptable 我需要知道這段代碼中的問題是什么,以及要進行哪些更改才能使這段代碼運行。

您需要轉換為字符串才能反轉和比較:

def largest_palindrome():                        # <-- arguments are not needed
    for y in (x for x in range(9801, 100, -1)):  # use a generator, that iterates from largest to smallest. 
        if str(y) == str(y)[::-1]:
            return y                             # early exit when largest match is found (it will be the first)

print(largest_palindrome())

劇透警告:

9779

作為單班輪:

max([x for x in range(9801, 100, -1) if str(x) == str(x)[::-1]])

作為一個線性發生器

(感謝@Austin 在評論中):

next(x for x in range(9801, 100, -1) if str(x) == str(x)[::-1])

Reblochon 的答案並沒有解決問題,因為它只在可能來自兩個兩位數的最小和最大數字之間進行迭代。 它不會遍歷兩位數。

def largest_palindrome():
    lastBiggestProduct = 0;
    lastBiggestNumb = 10;
    for firstNum in range(10,100):
        a = list(range(lastBiggestNumb,firstNum))
        a.extend(range(firstNum+1,100))
        for secondNum in a:
            prod = firstNum*secondNum
            if(prod>lastBiggestProduct and str(prod) == str(prod)[::-1]):
                lastBiggestProduct = firstNum*secondNum
                lastBiggestNumb = secondNum
    return lastBiggestProduct


print(largest_palindrome())

那返回:

9009

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM