如果内部循环序列依赖于父循环的值,并且不能简化循环(如上面的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
因为} 上使用单个循环:
range()
序列是固定的,所以不需要使用嵌套的for
循环。相反,在^{接下来,删除其中一个重复并降低范围值;您可以从
ai
和bi
简单地计算^{ci
,范围超过23是没有意义的(因为ci
只有在ai + bi
小于等于24时才是1或更大):在这里
ci
可以是负数并不重要,因为ai * ai
总是一个正数。你知道吗请注意,上述方程有四个解,因此从第一个解出发可能不是正确答案。可以使用以下公式计算给定目标值的所有可能解:
这将返回一个生成器,因此可以使用^{} 一次请求单个解决方案:
如果内部循环序列依赖于父循环的值,并且不能简化循环(如上面的
ci = 25 - ai - bi
赋值),那么您可能需要使用嵌套循环。您总是可以用捕获的异常来打破这种结构;即使是标准的ValueError
也可以这样做,或者创建一个自定义异常:或者将循环嵌套在函数中并使用
return
:你也可以
或者
相关问题 更多 >
编程相关推荐