简体   繁体   中英

Debugging recursive function to se how many times it repeats a certain calculation

I have a fibonacci series defined by a recursive function. My assignment is to debug to see how many times the function repeats certain calculations when called. How many times does fib(3) needs to be calculated when calling fib(10).

I have tried to use the pycharm debugging tool but it gets me nowhere. I start by adding a breakpoint in the beginning of the code and clicked debug. Then i tried to follow the code step by step, by the step over f8. Is there some other ways to solve this other than using pycharm?

        if n < 3:
            return 1
        else:
            return fib(n-1) + fib (n-2)

You can create a global variable and assign it to zero. After calling your recursive function you can look the value of your repeat variable.

repeat = 0  # you need to declare outside of function

def recursive_function(n):
    global repeat # you need to use 'global' keyword in order to modify global variable
    repeat += 1
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fib(n-1) + fib (n-2)

recursive_function(7)
print(repeat)
# call tree looks like this:
#                  fib(5)  
#          fib(4)    +    fib(3)
#    fib(3) + fib(2)    fib(2) + fib(1)
#fib(2)+fib(1)    

You can define a decorator to log function calls:

from functools import wraps

def log_calls(func):
    @wraps(func)
    def logged(*args):
        print(f'call {func.__name__}({", ".join(map(repr, args))})')
        return func(*args)
    return logged

Instead of printing, you can of course also increment a counter or use a different means to track progress. You can also do the printing conditionally, eg if args equals 3.

Applying this decorator to your function makes all calls visible:

@log_calls
def fib(n):
    return 1 if n < 3 else fib(n - 1) + fib(n - 2)

For example, fib(5) calls fib(3) twice:

>>> fib(5)
call fib(5)
call fib(4)
call fib(3)
call fib(2)
call fib(1)
call fib(2)
call fib(3)
call fib(2)
call fib(1)

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