From the course: Python: Recursion

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Memoization in Python

Memoization in Python - Python Tutorial

From the course: Python: Recursion

Start my 1-month free trial

Memoization in Python

- [Instructor] Another area where you need to be very careful when using recursion is a complexity in terms of time. Now, a very good illustration of this is with the Fibonacci function that we looked at earlier. So if you look at all the various function calls that you need to calculate, f6. You need to calculate f5 and f5 needs to calculate f3 and f4, and f3 needs to calculate f1 and f2. And if you notice there's a lot of repetition in these various function calls. On the next slide, you can see in fact where the only original calls that we needed to make were f5, f4, f3, f2, and f1, and there was all of this duplicate work going on. Now, memoization is an important technique for optimizing recursive algorithms. Basic idea is that we create a cache of previously calculated results to avoid duplication of work. Let's look at this in Python. So we have here fib. This is exactly the same code as we had previously.…

Contents