简体   繁体   中英

Number of recursive function calls

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)

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM