Skip to content

Question 33

What will the following code print?

def f(n):
    if n == 0:
        return 1
    else:
        return 1+g(n-1)

def g(n):
    if n == 0:
        return 1
    else:
        return 1+f(n-2)

print(f(10))
Hint

Trace the values passed into f() and g() carefully as you run through the nested loop structure.

Solution
f(10)
= 1 + g(9)
= 1 + [ 1 + f(7) ]
= 1 + 1 + [ 1 + g(6) ]
= 1 + 1 + 1 + [ 1 + f(4) ]
= 1 + 1 + 1 + 1 + [ 1 + g(3) ]
= 1 + 1 + 1 + 1 + 1 + [ 1 + f(1) ]
= 1 + 1 + 1 + 1 + 1 + 1 + [ 1 + g(0) ]
= 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
= 8
Answer
8