Javatpoint Logo
Javatpoint Logo

Memoization using Decorators in Python

The programming technique where a function calls itself repeatedly till it meets the termination condition is called recursion. Recursion is used for calculating Fibonacci series, factorial, and many more. However, there can be an issue while using recursion that the sub-problem which has been already solved might get solved again, which could get added to an overhead.

Memoization is the technique used for recording the average results so that it can be used to prevent the repetition of the calculated result and speed up the programs. This can also be used for improving the result of the program that is using recursion technique. In Python, memorization can be done by using the decorator function.

Let's understand it with an example of calculating the factorial of a given number by using recursion technique.

Example:

Output:

The factorial of the number is:  5040

We can optimize the above program with memoization by using decorators:

Example:

Output:

The factorial of the number is:  5040

Explanation:

  1. At first, we have defined a function called "memoization_factorial". The main objective of defining it is to store the average results in the variable called "memory_1".
  2. Then, we defined the second function called "factorial" for calculating the factorial of the number. We have annotated it by a decorator, which is the "memoization_factorial function. The factorial function is having access to the memory_1 variable. The annotation is equivalent to writing:
    factorial = memoization_factorial(factorial)
  3. When we call factorial(7), the recursion operation will take place in addition to the storage of average results. Whenever a calculation needs to be done; it will be checked if the result is available in the "memory_1" variable or not. If the results are available, then it will use the available results; otherwise, it will calculate the value and store it in the "memory_1" variable.

Conclusion

In this tutorial, we have discussed how we can use memoization with the help of a decorator in Python to avoid the repeating calculation of the same problem in recursion.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA