查找由两个3位数组成的乘积所产生的最大回文

时间:2019-05-07 23:20:46

标签: python python-3.x

我编写了程序,但是我想知道如何编辑并在输出中显示从中获得输出的两个产品:

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)

1 个答案:

答案 0 :(得分:1)

以与更新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
相关问题