Tracking the number of recursive calls without using global variables in Python

How to track the number of recursive calls without using global variables in Python. For example, how to change the following function to track the number of calls?

def f(n): if n == 1: return 1 else: return n * f(n-1) print f(5) 
+4
source share
5 answers

As Delnan said, if you want all calls ever to be impossible without a global one, I assume that you just need the call depth, for which you just need to add the return value

 def f(n): if n == 1: return 1,0 else: x, call_depth= f(n-1) return n * x, call_depth+1 

If you are dealing with multiple recursive calls, you can max(call_depth1, call_depth2) make max(call_depth1, call_depth2) (depth of a long call tree) or simply sum two (total number of actual calls)

+6
source

Here's a neat trick that doesn't use the global one: you can cross out the counter in the function itself.

 def f(n): f.count += 1 if n == 1: return 1 else: return n * f(n-1) 

Then:

 >>> f.count = 0 # initialize the counter >>> f(5) 120 >>> f.count 5 >>> f(30) 265252859812191058636308480000000L >>> f.count 35 

In any case, this handles the case of "all calls ever."

+10
source

This method will give you the total number of times the function was executed:

 def f(n): if hasattr(f,"count"): f.count += 1 else: f.count = 1 if n == 1: return 1 else: return n * f(n-1) 
+6
source

Here we use a method that uses a stack instead of global variables. As shown, it counts the number of function calls, including the initial, and not just the number of recursive calls made by the function itself. To do this, simply move ncalls += 1 to the beginning of the else .

 def f(n, ncalls=0): ncalls += 1 if n == 1: return 1, ncalls else: res, ncalls = f(n-1, ncalls) return n * res, ncalls for n in xrange(1, 6): print 'f({}): {:4d} ({} calls)'.format(n, *f(n)) 

Output:

 f(1): 1 (1 calls) f(2): 2 (2 calls) f(3): 6 (3 calls) f(4): 24 (4 calls) f(5): 120 (5 calls) 
+3
source

You can add an argument to count the number of calls (you would need to change something), where it increases at the beginning of the function.

0
source

All Articles