Reputation: 15
I'm a total beginner at Python and I was wondering how to get the number of recursive function calls ? is it 2^n (if n is the argument given)
Upvotes: 0
Views: 104
Reputation: 1952
The amount of calls completely depends on the algorithm. Sometimes it is 2**n, but other times it could be n! or a quadratic, or anything else.
To work out how many it is, you can you use my method. This might get shunned by some other users, but using a global counter is a quick and easy way to count the amount of function calls.
function_calls = 0
def fibonacci_recursive(n):
global function_calls
function_calls += 1
if n == 0:
return 1
elif n == 1:
return 1
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
ans = fibonacci_recursive(20)
print("There were",function_calls,"function calls.")
Upvotes: 1