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.py118 chars7 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.py94 chars11 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