Tanzir Uddin
Tanzir Uddin

Reputation: 61

How to calculate the number of recursive call?

As ex. I write fibonancci code by recursion -

def fib(n):
    x = 0
    if n == 0 or n == 1:
        return 1
    else:
        print('computing : ', n) # this show the recursive call.
        x = x +1
        print('recursive call no total : ',x) # this show the how many number of recursive call.
        return fib(n-1) + fib(n-2)

but this print , recursive call no: 1 recursive call no: 1 and it's go on with 1 .

theres some problem occur. I can't figure it out. The value of x doesn't increase's as it's not a iterative processes. But how i can increase the value of x through each recursive call ?

Using a global variable , i tried to solve the ans . Code's may like below-

def fib(n):
    global numcalls
    numcalls += 1 #this will increment with every fib() call
    if n ==0 or n ==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
    print('numcalls =', numcalls)

Then calling the function with, numcalls = 0 fib(5)

Is the code above ok ? If not , then suggest something abouts bugs .

Upvotes: 1

Views: 4034

Answers (2)

Garima Singh
Garima Singh

Reputation: 223

few ways of doing this

we can use counter as you tried with slight changes:

def fib(n):
    if n == 0 or n == 1:
        return 1
    else:
        print('computing : ', n)  # this show the recursive call.
        fib.x = fib.x + 1
        # this show the how many number of recursive call.
        print('recursive call no : ', fib.x)
        return fib(n - 1) + fib(n - 2)

fib.x = 0
fib(6)

we can also use decoration see Python: static variable decorator

A side effect of this is that you would manually have to reset fib.x = 0 every time you call fib, one way of handling this within the function is by taking an extra argument that will only be specified by recursive calls to not reset fib.x = 0:

def fib(n, _from_user=True):
    if _from_user: #default was used so the call was from the user, set x to 0 now
        fib.x = 0
    if n == 0 or n == 1:
        return 1
    else:
        print('computing : ', n)  # this show the recursive call.
        fib.x = fib.x + 1
        # this show the how many number of recursive call.
        print('recursive call no : ', fib.x)
         #pass _from_user =  False for sub calls
        return fib(n - 1, False) + fib(n - 2, False)

fib(6)

Upvotes: 2

Tanzir Uddin
Tanzir Uddin

Reputation: 61

Using a global variable , i tried to solve the ans . Code's may like below-

def fib(n):
    global numcalls
    numcalls += 1 #this will increment with every fib() call
    if n ==0 or n ==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)
    print('numcalls =', numcalls)

Then calling the function with, numcalls = 0 fib(5)

Is the code above ok ? If not , then suggest something abouts bugs .

Upvotes: 0

Related Questions