簡體   English   中英

查找由兩個3位數組成的乘積所產生的最大回文

[英]Find the largest palindrome made from the product of two 3-digit numbers, just a small edit needed

我寫了程序,但是我不知道如何編輯和顯示輸出中的兩個產品:

def check_palindrome(s):
     """Checks whether the given string is palindrome"""
     return s == s[::-1]
max_product = 0
for i in range(999, 900, -1):
    for j in range(i, 900, -1):
        product = i * j
        if check_palindrome(str(product)):
            max_product = max(max_product, product)
print(max_product)

以相同的方式更新max_product ,可以使用另外兩個變量( ab ),並在必要時(當product大於max_product時)繼續更新它們:

def check_palindrome(s):
     """Checks whether the given string is palindrome"""
     return s == s[::-1]

max_product = a = b = 0

for i in range(999, 900, -1):
    for j in range(i, 900, -1):
        product = i * j
        if check_palindrome(str(product)):
            if product > max_product:     # if greater product
                max_product = product     # update max_product
                a = i                     # update a
                b = j                     # update b

print('%d * %d = %d' % (a, b, max_product))

另外,您可以將其用於更新和較短的代碼:

max_product, a, b = product, i, j

暫無
暫無

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

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