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 1
else:
return n * f(n-1)
print f(5)
Thus in our case, the number of recursive calls is n0 +n2 = 2n0 −1, which means that the total number of recursive calls is equal to 2Fn+1 − 1. This way, we have reached the same result with [2], however, in a much simpler way from the mathematical and pedagogical point of view.
Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.
sys. getrecursionlimit(): Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().
A recursive implementation may have more than one base case, or more than one recursive step. For example, the Fibonacci function has two base cases, n=0 and n=1.
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 += 1
if n == 1:
return 1
else:
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.
As delnan said, if you want all calls ever, it's impossible without a global, so I'm assuming you just want the call depth, for which you just need to add a 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're dealing with several recursive calls, you can do a max(call_depth1, call_depth2)
(depth of longest call tree) or just sum the two (total number of actual calls)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With