...

/

The Fibonacci Numbers Algorithm with Memoization

The Fibonacci Numbers Algorithm with Memoization

In this lesson, we will employ memoization in the Fibonacci numbers algorithm.

Optimizing Fibonacci number’s algorithm

Let’s revisit the Fibonacci numbers algorithm from an earlier lesson of this course.

Press + to interact
def fib(n):
if n == 0: # base case 1
return 0
if n == 1: # base case 2
return 1
else: # recursive step
return fib(n-1) + fib(n-2)
print (fib(10))

We have also reproduced a dry run of Fib(6) below to visualize how this algorithm runs.

Memoization

Now let’s store the results of every evaluated Fibonacci number and reuse it whenever it is needed ...