CodeBlanks Logo Icon CodeBlanks

Summary - Memoization

Call memoized Fibonacci and print the result in a mini task.

Summary - Memoization

Memoization is the caching technique that prevents recomputation in recursive solutions. It drops complexity from exponential to polynomial.

In this mini task you will call memoized Fibonacci and print the result; combine all steps.

Memoization is the top-down form of dynamic programming; recursion + cache.

Practice Print memoized Fibonacci

Write fib_memo_print(n). Call fib_memo(n, {}) and print with print(). Output of fib_memo_print(15): 610.

Starter code

solution.py
def fib_memo_print(n):
    # Print memoized Fibonacci

Sample solution

solution.py
def fib_memo_print(n):
    # Print memoized Fibonacci
    def fib_memo(n, memo):
        if n in memo:
            return memo[n]
        if n <= 1:
            return n
        memo[n] = fib_memo(n - 1, memo) + fib_memo(n - 2, memo)
        return memo[n]
    print(fib_memo(n, {}))
fib_memo_print(15)

Expected output

610

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Summary - Memoization: match the terms

Term Meaning
memoization Cache
dict Dictionary
recursion Self-call
cache Fast

2 Base condition

Question
if n <= ____:
Answer
if n <= 1:

Explanation: 1 is right.

3 Memoization is part of which technique?

  • Divide and conquer
  • Greedy
  • Dynamic programming Correct answer
  • Backtracking

Explanation: Dynamic programming.

All lessons in Advanced