create a memoised function to add two numbers in python

To create a memoised function to add two numbers in Python, we can use a decorator that caches the result of the function for a given set of arguments, so that if the function is called again with the same arguments, it returns the cached result instead of re-evaluating the function. Here's an example implementation:

main.py
from functools import lru_cache

@lru_cache(maxsize=None)
def add(x, y):
    print("Calculating...")
    return x + y
118 chars
7 lines

In this code, the @lru_cache(maxsize=None) decorator applies the memoization logic to the add function. The maxsize=None parameter tells lru_cache to cache all the results indefinitely, which is convenient for small functions like this one.

Now, when we call the add function with two numbers, the function first checks if the result has already been cached for these input values. If it has, it returns the cached result immediately, without recomputing the sum. If it hasn't, it prints "Calculating..." to indicate that it's doing the calculation, then returns the sum and caches it for future reference.

main.py
>>> add(2, 3)
Calculating...
5
>>> add(2, 3)
5
>>> add(3, 4)
Calculating...
7
>>> add(3, 4)
7
94 chars
11 lines

As we can see from the output, the first call to add(2, 3) requires a calculation, but the second call returns the cached result without a calculation. The same happens for the inputs (3, 4). This memoization technique can help optimize the performance of functions that are computationally expensive or frequently called with the same arguments.

gistlibby LogSnag