python - 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()
解决方案
如果我正确理解您的意图,您可以将事物重构为一个生成器,该生成器在给定范围内产生所有可能的回文,然后用于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)
推荐阅读
- java - 通用类型的流图
- jquery - 使用 jQuery 从 Fancybox 中的图库 html 元素中选择数据属性
- amazon-web-services - 当所有正在运行的 pod 的总和超过节点容量时,节点处于“未就绪”状态
- google-cloud-platform - 如何在 GQL 上大写或小写数据存储字段名称(例如 - 通过 Web 表单输入的用户的姓氏或第一个)?
- html - 如何在 HTML 页面上添加 MP3 文件作为背景
- python - 将 python 列表转换为字符串(列表包括一些字符串)
- python - 即使一个语句失败,如何遍历你的 python 脚本?
- sql-server - SQL Server:使用 LIKE 运算符搜索 2 个表
- python - 为什么烧瓶会抛出类属性错误
- matlab - 为什么 datetime() 输出中的 4 天对应于 Matlab 中 datestr() 的 1 个月和 4 天?