繁体   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