python - Python 中的多个 for 循环中断

标签 python for-loop break

<分区>

我正在解决 Euler 的项目,现在正在尝试解决 9 个任务。

我找到的解决方案是在 3 个嵌套循环中:

for ai in range(1, 100):
   for bi in range(1, 100):
      for ci in range(1,100):
          if ai + bi + ci == 25 and ai * ai = ci:
             break

但是最后如果找到循环的解决方案,我想打破所有循环。 这可行吗?我想过使用一些标志,但它会额外检查每个步骤并使执行时间更长。

最佳答案

因为您的 range() 序列是固定的,所以您不需要使用嵌套的 for 循环。相反,在 itertools.product() 上使用单个循环:

from itertools import product

for ai, bi, ci in product(range(1, 100), repeat=3):
    if ai + bi + ci == 25 and ai * ai == ci:
         break

接下来,删除其中一个重复并降低范围值;您可以根据 aibi 简单地计算 ci,超出 23 的范围是没有意义的(因为 ci 仅当 ai + bi 为 24 或更小时才为 1 或更大):​​

for ai, bi in product(range(1, 23), repeat=2):
    ci = 25 - ai - bi
    if ai * ai == ci:
         break

ci 在这里可以为负数并不重要,因为 ai * ai 将始终为正数。

请注意,上面的等式有四个解,因此第一个解可能不是正确答案。您可以使用以下方法计算给定目标值的所有可能解决方案:

def triplets(target):
    return (
        (ai, bi, target - ai - bi)
        for ai, bi in product(range(1, target - 2), repeat=2)
        if ai * ai == target - ai - bi
    )

这会返回一个生成器,因此可以使用 next() 一次请求一个解决方案:

gen = triplets(25)
print(next(gen, None))

如果您的内部循环序列依赖于父循环的值,并且您无法简化循环(如上面的 ci = 25 - ai - bi 赋值),那么您 < em>也许 需要使用嵌套循环。您总是可以在捕获到异常的情况下突破此类结构;即使是标准的 ValueError 也可以,或者创​​建一个自定义异常:

class Break(Exception):
    pass

try:
    for ai in <some_sequence>:
        for bi in range(<based on ai>):
            if <condition>:
                raise Break
except Break:
    # nested set of loops has exited

或者将循环嵌套在函数中并使用return:

def nested_loops(<arguments>):
    for ai in <some_sequence>:
        for bi in range(<based on ai>):
            if <condition>:
                return ai, bi

关于python - Python 中的多个 for 循环中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099759/

相关文章:

loops - 如何在柏树中停止循环

python - 如何在每次创建页面时生成一定长度的随机 url?

c++ - OpenGL GL_LINE_STRIP 在 glEnd 之后给出错误 1281(无效值)

python - 无法在MacOS上的python中导入opengl.gl

c - for 循环在 C 中不能正确递增

c++ - Break 在不该执行的时候执行

java - 请解释Labeled Statements的用法

python - 如何在 iPython 笔记本中预览 Pandas DataFrame 的一部分?

for-loop - Rust 错误预期类型 `()` 找到类型 `(i32, i32)`

javascript - 如何循环遍历具有多个对象的数组并仅在 Javascript 中列出某些元素?