Question Details

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 Answer

Correct Answer :

8

Solution :

The correct answer is 8.

To find the value of mystery(4), we can trace the recursive function step-by-step.
The definition of the function is:
For any input n:
1. If n0, the function returns 1 (this is our base case).
2. Otherwise, for n>0, the function returns:

mystery(n)=mystery(n-1)+mystery(n-2)

Let us calculate the values starting from the smallest inputs up to 4:

Base Cases:
For any value less than or equal to 0, the function returns 1:

mystery(0)=1

mystery(-1)=1

Step 1: Calculate mystery(1)

mystery(1)=mystery(0)+mystery(-1)

mystery(1)=1+1=2

Step 2: Calculate mystery(2)

mystery(2)=mystery(1)+mystery(0)

mystery(2)=2+1=3

Step 3: Calculate mystery(3)

mystery(3)=mystery(2)+mystery(1)

mystery(3)=3+2=5

Step 4: Calculate mystery(4)

mystery(4)=mystery(3)+mystery(2)

mystery(4)=5+3=8

Thus, the value of mystery(4) is 8.

Unlock Our Free Library

Access expert-curated educational resources and study materials—completely free.

Ask AI Tutor
5 left
Q1 View Question & Options
AI Tutor is solving this question...
Reading question context & options...