0

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!

L_Pav
  • 281
  • 1
  • 3
  • 11
  • You can always pass and return a counter variable to the function. Alternatively, have a look at this question about [Python "static" variables](http://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function). –  Apr 24 '16 at 22:25

3 Answers3

1

You can attach an attribute to the function:

def f(a, b):
    f.num += 1
    if a <= 0 or b <= 0:
        ...

Result:

>>> f.num = 0
>>> f(0, 0)
0
>>> print(f.num)
1
>>> f.num = 0
>>> f(3, 5)
4
>>> print(f.num)
13
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

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])
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

I don't trust Global variable because of the highly available scope i.e. global variables are accessible to everyone. Instead, you can keep a recursion variable which counts the number of times the function has been called.

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

    return [s,count]
silent_dev
  • 1,566
  • 3
  • 20
  • 45