Question:

A recursive function is given:
def mystery(n): 
if n $<=$ 0: 
return 1 
else: 
return mystery(n-1) + mystery(n-2) 
Find the value of mystery(4). 

Show Hint

When evaluating a simple recursive function like this, it's often safer and faster to compute the values iteratively from the bottom up, rather than drawing a large recursion tree. This avoids recomputing the same values multiple times and reduces the chance of error. This technique is known as dynamic programming or memoization.
Updated On: Feb 23, 2026
Hide Solution
collegedunia
Verified By Collegedunia

Correct Answer: 8

Solution and Explanation

Step 1: Understanding the Question:
We are given a recursive function `mystery(n)` and asked to calculate its value for an input of `n=4`. The function's definition is similar to the Fibonacci sequence, but with different base cases.
Step 2: Analyzing the Recurrence Relation:
- Recurrence: `mystery(n) = mystery(n-1) + mystery(n-2)` for n> 0.
- Base Cases: `mystery(n) = 1` for n $\le$ 0. This means `mystery(0) = 1` and `mystery(-1) = 1`, `mystery(-2) = 1`, etc.
Step 3: Calculating the Values Iteratively:
We can compute the values from the base cases up to n=4.
- `mystery(0) = 1` (by base case)
- `mystery(1) = mystery(0) + mystery(-1)`. Since -1 $\le$ 0, `mystery(-1) = 1`.
`mystery(1) = 1 + 1 = 2`
- `mystery(2) = mystery(1) + mystery(0) = 2 + 1 = 3`
- `mystery(3) = mystery(2) + mystery(1) = 3 + 2 = 5`
- `mystery(4) = mystery(3) + mystery(2) = 5 + 3 = 8`
Step 4: Final Answer:
The value of mystery(4) is 8.
Was this answer helpful?
0
0

Questions Asked in GATE DA exam

View More Questions