Complexity and efficiency · 14 / 15 Exercise Hard

Fibonacci with memoization

Objective

Create a Python program that computes the Fibonacci number in two ways and compares how many calls each one makes. The simple recursive version is exponential; with memoization (storing already computed results) it becomes linear.

Instructions

  • Read an integer n (between 0 and 25).
  • Write fib_simple(n), which counts every call and uses fib(n-1) + fib(n-2) (with fib(0) = 0 and fib(1) = 1).
  • Write fib_memo(n) the same way, but with a dictionary memo: count every call (even those answered from the dictionary) and, before computing, return the stored result if it already exists.
  • Show Fibonacci(n) = v, Calls without memoization: x and Calls with memoization: y.
Input
10
Output
Fibonacci(10) = 55
Calls without memoization: 177
Calls with memoization: 19

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise