Using enumerate function in while loops

I have several mathematical algorithms that use iteration to search for the right answer. Here is one example:

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 

I want to count how many times the algorithm goes through the loop to get a and b. However this is not a for function and it isn't a list, so I can't clearly indicate what objects do I want to count if I use enumerate. Is there a way to count those loops?

Note: I am not trying to change the code itself. I am really searching for a way to count iterations in a while loop, which I can then use for other cases.

2 Answers

The simplest answer if you need a counter outside of a for loop is to count manually using a simple variable and addition inside your while loop:

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

There is an alternative case - if each step of your iteration has a meanigful value to yield, you may want your loop to be a generator, and then use for loop and enumerate(). This makes most sense where you care about which step you are on, not just the count at the end. E.g:

def produce_steps(): while condition: ... yield step_value for count, step_value in enumerate(produce_steps()): ... 

For a counter I use count from itertools:

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

and so on...

Syntax

count(start=0, step=1) 

Docs

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

Ref. itertools.count

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like