I am writing a branch and bound algorithm in python and I am trying to efficiently display the progress. The algorithm uses recursion and I couldn't figure out any way to make it iterative. I am wondering if there is a tqdm like module for recursive functions or at least a way to implement a progress bar with recursive functions? For example, if I was writing an iterative factorial function in python with the tqdm module I would do this:
import tqdm
def factorial(n):
end_product = 1
for i in tqdm(range(1, n)):
end_product *= i
return end_product
How would I implement a progress bar on a recursive function like this:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
progress_bar(factorial(1000))
One solution is initialize progress bar with total=
parameter and then call .update()
method in each call of recursion.
Something along the lines of this:
from time import sleep
from tqdm import tqdm
def factorial(n, bar):
bar.update(1)
sleep(0.01) # slow-down things a little bit
if n == 1:
return 1
else:
return n * factorial(n-1, bar)
n = 500
bar = tqdm(total=n)
factorial(n, bar=bar)