首页 > 解决方案 > Python循环在99999之后停止输出,即使它应该继续

问题描述

此代码旨在从 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()

标签: python

解决方案


如果我正确理解您的意图,您可以将事物重构为一个生成器,该生成器在给定范围内产生所有可能的回文,然后用于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)

推荐阅读