Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a memo dictionary for caching results.
DSA Python
def fib(n, [1]): if n <= 1: return n if n in memo: return memo[n] memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n] memo = {} print(fib(5, memo))
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name than the memo dictionary.
Not passing the memo dictionary in recursive calls.
✗ Incorrect
The memo dictionary is passed as 'memo' to cache computed Fibonacci values.
2fill in blank
mediumComplete the code to check if the result is already cached.
DSA Python
def fib(n, memo): if n <= 1: return n if [1] in memo: return memo[n] memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if 'memo' or 'cache' is in memo instead of 'n'.
Using the function name instead of the key.
✗ Incorrect
We check if 'n' is a key in the memo dictionary to return cached results.
3fill in blank
hardFix the error in the recursive call to use memoization correctly.
DSA Python
def fib(n, memo): if n <= 1: return n if n in memo: return memo[n] memo[n] = fib(n-1, [1]) + fib(n-2, memo) return memo[n]
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the wrong variable instead of the memo dictionary.
Not passing the memo dictionary in one of the recursive calls.
✗ Incorrect
The memo dictionary must be passed in all recursive calls to cache results properly.
4fill in blank
hardFill both blanks to create a memoized factorial function.
DSA Python
def factorial(n, [1]): if n == 0: return 1 if n in [2]: return memo[n] memo[n] = n * factorial(n-1, memo) return memo[n] memo = {} print(factorial(5, memo))
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the memo dictionary in parameter and inside the function.
Not checking the memo dictionary before recursive call.
✗ Incorrect
The memo dictionary is named 'memo' and used consistently as parameter and inside the function.
5fill in blank
hardFill all three blanks to create a memoized function that sums numbers up to n.
DSA Python
def sum_to_n(n, [1]): if n == 0: return 0 if n in [2]: return memo[n] memo[n] = n + sum_to_n(n-1, [3]) return memo[n] memo = {} print(sum_to_n(5, memo))
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the memo dictionary in different places.
Not passing the memo dictionary in recursive calls.
✗ Incorrect
The memo dictionary is consistently named 'memo' and passed as parameter and used inside the function.
