Python中的多个forloop中断

2024-10-03 09:13:51 发布

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

我正在解决Euler的项目,现在triyn要解决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

但当最后一次,如果找到循环的解继续,我想打破所有的循环。 有可能吗?我考虑使用一些标志,但这是对每个步骤的附加检查,使执行时间更长。你知道吗


Tags: and项目inciforif标志range
2条回答

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

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
    )

这将返回一个生成器,因此可以使用^{}一次请求单个解决方案:

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

如果内部循环序列依赖于父循环的值,并且不能简化循环(如上面的ci = 25 - ai - bi赋值),那么您可能需要使用嵌套循环。您总是可以用捕获的异常来打破这种结构;即使是标准的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

你也可以

  • 将其放入函数中,并在到达该值时立即返回该值

或者

  • 达到值后引发异常,并传递:
try:
    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:
                 raise BreakE
except BreakE:
    pass

相关问题 更多 >