-3

Here's the code:

def f(k):
    if k<3:
        return 1
    return f(k-1)+f(k-2)+f(k-3)

Thanks in advance!

Sander
  • 9
  • 2
  • This question needs more information. What is the expected output for this function? Does it return the wrong output? For which input? – trincot Oct 05 '21 at 10:43
  • 2
    What do you mean by *"number of subtractions"*? The number of (recursive) calls to the function? – user2390182 Oct 05 '21 at 10:46

2 Answers2

5

You could write a decorator to count calls to the function:

def count(func):
    def wrapper(*args, **kwargs):
        if kwargs.pop("reset", False):
            wrapper.calls = 0
        wrapper.calls += 1
        return func(*args, **kwargs)
    wrapper.calls = 0
    return wrapper
    
@count
def f(k):
    if k<3:
        return 1
    return f(k-1)+f(k-2)+f(k-3)

Now you can count function calls:

>>> f(5, reset=True)
9
>>> f.calls
13
>>> f(23, reset=True)
532159
>>> f.calls
798251
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

I got the same output as @schwobaseggl by using global variable:

count = 0
def f(k):
    global count
    count+=1
    if k<3:
        return 1
    
    return f(k-1)+f(k-2)+f(k-3)
print(f(23))
print(count)
quamrana
  • 37,849
  • 12
  • 53
  • 71
Shreyas Prakash
  • 604
  • 4
  • 11
  • 1
    As a programmer you should try very, *very*, **very** hard not to use globals. – quamrana Oct 05 '21 at 10:59
  • 1
    Thanks for the tip @quamrana. I will keep this in mind. – Shreyas Prakash Oct 05 '21 at 11:00
  • 2
    I searched and got this, explaining why we shouldn't use global variables. https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – Shreyas Prakash Oct 05 '21 at 11:04
  • 1
    Yes, in the case of your answer, there is no other function which could use `count` to count the number of calls. Other functions would need their own count. This is what the decorator in the other answer neatly encapsulates. – quamrana Oct 05 '21 at 11:08