How to track the number of recursive calls without using global variables in Python. For example, how to modify the following function to keep track the number of calls?
def f(n):if n == 1:return 1else:return n * f(n-1)print f(5)
How to track the number of recursive calls without using global variables in Python. For example, how to modify the following function to keep track the number of calls?
def f(n):if n == 1:return 1else:return n * f(n-1)print f(5)
Here's a neat trick that doesn't use a global: you can stash the counter in the function itself.
def f(n):f.count += 1if n == 1:return 1else:return n * f(n-1)
After which:
>>> f.count = 0 # initialize the counter
>>> f(5)
120
>>> f.count
5
>>> f(30)
265252859812191058636308480000000L
>>> f.count
35
This handles the "all calls ever" case, anyhow.