Memoization Using Decorators:

A method in which a function calls itself repeatedly unless a termination condition is met is known as recursion. Recursion can be useful in many places such as factorials, calculation of Fibonacci series, etc. But the main problem is that a sub-problem which is already in the recursion tree we can repeatedly solve it again. This will add to overhead in python while using it in a data science project.

In memorization technique, the intermediate results are recorded, which helps in avoiding repeated calculations. This, in turn, speeds up the program. It is a good way of optimizing the programs which use recursion. In order to perform memoization we need function decorators.

Now we will consider two examples, one without using memoization and the other using memoization.

python for data science

Explanation to above Example:

  • We have defined a function memoize_factorial, and its main purpose is storing intermediate results in the variable memory.
  • The second function, facto, is ther for calculating the factorial. A decorator (memoize_factorial) annotates this function. As we have seen in closures, the facto can access the memory variable. The annotation is similar to

  • As soon as we call the facto(5), the recursion operation takes place along with addition of storage of intermediate results. Whenever a calculation needs to be performed, it is first checked whether it is available in the memory. In the case of its availability, it is there or else, the value is calculated and then stored in memory.

If you want to learn more about python for data science, you can check this and this for that.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.