Python循环在99999之后停止输出,即使它应该继续

2024-10-03 21:25:53 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码旨在从2个3位数字中查找最大回文,但在最终回文之前就停止了puttign。请帮忙

def palindrome():

    pdrome = -1
    for num in range(100, 1000):
        for num2 in range(100, 1000):
            product = num * num2
            sproduct = str(product)
            length = len(sproduct)
            if length % 2 == 0:
                string1 = sproduct[0:length // 2]
                string2 = sproduct[(length//2) + 1:]
            else:
                string1 = sproduct[0:(length//2)]
                string2 = sproduct[((length//2) + 1):]
            rstring = string2[::-1]
            if string1 == rstring:
                    pdrome = product
    print(pdrome)


palindrome()

Tags: 代码inforifrangeproductlengthnum
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:53

如果我正确理解您的意图,您可以将内容重构为一个生成器,生成给定范围内所有可能的回文,然后使用max()获得最高回文:

def generate_palindromes(a, b):
    for n1 in range(a, b):
        for n2 in range(n1 + 1, b):  # no need to go through all combinations
            number = n1 * n2
            str_number = str(number)
            if str_number == str_number[::-1]:  # It's the same when reversed?
                yield (number, n1, n2)  # Return a 3-tuple, so we can retrieve the factors


highest_palindrome, n1, n2 = max(generate_palindromes(100, 1000))
print(highest_palindrome, n1, n2)

相关问题 更多 >