Question:

A recursive function in Python is given.
def mystery(n):
    if n <= 0:
        return 1
    else:
        return mystery(n-1) + mystery(n-2)
Now, consider the following function call:
mystery(4)
Assume that a typical runtime stack is used to manage function calls. Each function call is pushed onto the stack and removed only after it finishes execution.
Which of the following options denotes the total number of function calls (i.e., the total number of stack activations), including the initial call, to compute mystery(4)?

Show Hint

Set up T(n) = 1 + T(n-1) + T(n-2) with T(n)=1 for n<=0, then build up to T(4).
Updated On: Jul 22, 2026
  • 5
  • 9
  • 15
  • 17
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation

Step 1: Set up a formula for the total number of calls.
Let \(T(n)\) be the total number of function-call activations made while computing \(mystery(n)\), counting the call itself. For \(n \leq 0\), the function returns immediately with no further recursive calls, so \(T(n) = 1\) in that base case. For \(n > 0\), the call makes 1 activation for itself, plus it calls \(mystery(n-1)\) and \(mystery(n-2)\), contributing all of their activations too. So
\[ T(n) = 1 + T(n-1) + T(n-2), \quad n > 0 \]

Step 2: Compute the base cases.
\(T(0) = 1\) (base case, no recursive calls).
\(T(-1) = 1\) (also a base case, since \(-1 \leq 0\)).

Step 3: Build up \(T(1)\) through \(T(4)\) using the recursion.
\(T(1) = 1 + T(0) + T(-1) = 1 + 1 + 1 = 3\)
\(T(2) = 1 + T(1) + T(0) = 1 + 3 + 1 = 5\)
\(T(3) = 1 + T(2) + T(1) = 1 + 5 + 3 = 9\)
\(T(4) = 1 + T(3) + T(2) = 1 + 9 + 5 = 15\)

Step 4: Double check by picturing the call tree shape.
\(mystery(4)\) calls \(mystery(3)\) and \(mystery(2)\); \(mystery(3)\) calls \(mystery(2)\) and \(mystery(1)\); and so on, exactly mirroring the Fibonacci recursion tree. Counting every node in this tree, including leaves that hit the base case, gives the same total of 15.

Step 5: Compare with the options.
5 would be \(T(2)\), and 9 would be \(T(3)\); both undercount by stopping the recursion too early. 17 does not match any correct partial sum of this recursion. 15 matches \(T(4)\) computed above.

Final Answer:
The total number of function calls to compute \(mystery(4)\) is 15, which is option (C).
Was this answer helpful?
0
0

Top GATE DA Data Science and Artificial Intelligence Questions

View More Questions

Top GATE DA Programming in Python Questions

View More Questions