在 while 循环中使用枚举函数

Using enumerate function in while loops

我有几种使用迭代来搜索正确答案的数学算法。这是一个例子:

def Bolzano(fonction, a, b, tol=0.000001):
    while abs(b - a) > tol:
        m = (a + b) / 2
        if sign(fonction(m)) == sign(fonction(a)):
            a = m
        else:
            b = m
    return a, b

我想统计算法经过多少次循环得到ab。但是,这不是 for 函数,也不是列表,因此如果我使用 enumerate,我无法清楚地指出我想计算哪些对象。有没有办法计算这些循环?

注意:我并不是要更改代码本身。我真的在寻找一种方法来计算 while 循环中的迭代次数,然后我可以将其用于其他情况。

如果您需要 for 循环之外的计数器,最简单的答案是使用简单的变量手动计数并在 while 循环内添加:

count = 0
while condition:
    ...
    count += 1

还有另一种情况 - 如果迭代的每个步骤对 yield 都有一个有意义的值,您可能希望循环是 generator,然后使用 for循环和 enumerate()。这在您关心您正在进行的步骤时最有意义,而不仅仅是最后的计数。例如:

def produce_steps():
    while condition:
        ...
        yield step_value

for count, step_value in enumerate(produce_steps()):
    ...

对于计数器,我使用 count from itertools:

from itertools import count
c = count(1)
>>>next(c)
1
>>>next(c)
2

等等...

语法

count(start=0, step=1)

文档

Make an iterator that returns evenly spaced values starting with number start.

参考。 itertools.count