Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. Here’s an example demonstrating how to implement memoization in Python using a decorator to optimize a recursive Fibonacci function.
# Memoization decorator
def memoize(func):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
result = func(*args)
cache[args] = result
return result
return wrapper
@memoize
def fibonacci_memoized(n):
"""Recursively calculate the nth Fibonacci number with memoization."""
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci_memoized(n - 1) + fibonacci_memoized(n - 2)
# Test the memoized Fibonacci function
print(f"Fibonacci of 10 with memoization: {fibonacci_memoized(10)}")
memoize function is a decorator that takes a function func as an argument and returns a wrapper function.wrapper function maintains a cache (dictionary) to store the results of previous function calls.wrapper is called, it first checks if the result for the given arguments is already in the cache.func, stores the result in the cache, and then returns the result.@memoize decorator, which optimizes the function by caching its results.n less than or equal to 0 (returning 0) and n equal to 1 (returning 1).n, it returns the sum of the Fibonacci numbers of n-1 and n-2.When you run the above code, you will get the following output:
Fibonacci of 10 with memoization: 55