Memoization using Decorators in PythonIn this tutorial, we will discuss one of the advance concepts of Python decorator. We assume that, you have basic understanding of the Python decorators. If not, you can learn from of Decorator in Python tutorial. What is Memoization?Before learning about the memoization, let's have a brief introduction of Recursion A recursion is a technique where a function calls itself repeatedly till the base case condition is met. For example calculation of Fibonacci series, factorial, etc. But it creates the problem with the recursion tree; there can be chances that the sub-problem that is already solved is being solved again, which leads to be overhead in the memory. To overcome such error, memoization comes into the play. Memoization is a programming technique which records the intermediate results so that it can be used to overlook the repeated calculations and makes the fast execution of program. This technique is used to optimize the recursion based program with the help of decorators. Let's understand the following example of calculating the factorial of a number using the recursion. Example Output: 120 The same program can be implemented using the memoization decorators. Example 2: Explanation In the above code
ConclusionIn this tutorial, we have explained the Python advance concept of decorator memoization. It is quite helpful in recursion tree problems. It reduces the memory heads. |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India