L_Pav L_Pav - 2 years ago 76
Python Question

How to find the number of times function f is executed?

The function f is defined as such:

def f(a, b):
if a <= 0 or b <= 0:
return a + b
else:
s = 0
if b * b % (a + b) != 0:
s += f(a, b - 3)
if a * a % (a + b) != 0:
s += f(a - 2, b)
if a == b - 1:
s += f(a - 3, b - 2)
return s


The question is: "How many times will a function "f" be executed, given f(4, 9)?" For example, for f(0, 0) function "f" will be executed once, since the first time is taken into account as well. Can someone explain to me, how I can find the number of executions? (Examples will be ideal.) Than you in advance!

Answer Source

You can increment a global counter, an int wrapped in a list, incrementing it in the function and printing the result after you call it:

i = [0]
def f(a, b):
    i[0] += 1
    if a <= 0 or b <= 0:
        return a + b
    else:
        s = 0
        if b * b % (a + b) != 0:
            s += f(a, b - 3)
        if a * a % (a + b) != 0:
            s += f(a - 2, b)
        if a == b - 1:
            s += f(a - 3, b - 2)

    return s

f(2, 34)
print(i[0])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download