4. Find the error in this recursive Fibonacci function and choose the correct fix:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-3)
medium
A. Add memoization dictionary to store results.
B. Change fib(n-3) to fib(n-2) to correctly sum previous two Fibonacci numbers.
C. Change base case n==0 to n<=0.
D. No error; function works correctly.
Solution
Step 1: Identify the recursive calls
The function calls fib(n-1) and fib(n-3), but Fibonacci sums fib(n-1) and fib(n-2).
Step 2: Correct the recursive call
Change fib(n-3) to fib(n-2) to follow Fibonacci definition properly.
Final Answer:
Change fib(n-3) to fib(n-2) to correctly sum previous two Fibonacci numbers. -> Option B
Quick Check:
Fibonacci sums fib(n-1) + fib(n-2) [OK]
Hint: Fibonacci sums previous two, not previous and third previous [OK]
Common Mistakes:
Using wrong recursive calls like fib(n-3)
Ignoring base cases
Assuming no error in recursion
5. You want to find the number of ways to climb a staircase of 4 steps, taking 1 or 2 steps at a time. Which approach best avoids repeated calculations and why?
def climb(n, memo={}):
if n in memo:
return memo[n]
if n <= 1:
return 1
memo[n] = climb(n-1, memo) + climb(n-2, memo)
return memo[n]
print(climb(4))
hard
A. Using dynamic programming with memoization to store and reuse results.
B. Using recursion but only calling climb(n-1) once.
C. Using a loop without storing previous results.
D. Using recursion alone without memoization, which repeats calculations.
Solution
Step 1: Understand the problem and code
The function counts ways to climb stairs using recursion with memoization to save results.
Step 2: Why memoization helps
Memoization avoids recalculating climb(n-1) and climb(n-2) multiple times, improving efficiency.
Final Answer:
Using dynamic programming with memoization to store and reuse results. -> Option A
Quick Check:
Memoization saves repeated work = DP [OK]
Hint: Memoize recursive calls to avoid repeated work [OK]
Common Mistakes:
Using recursion without memoization causing slow code
Using loops without storing previous results
Calling only one recursive branch
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.