摘要:记忆化是一种优化技术,用于通过存储昂贵的函数调用的结果并在再次出现相同的输入时重用它们来加速程序。在 Python 中,functools 模块提供了 lru_cache 装饰器,它提供了一种缓存函数结果的简单方法。在函数调用的计算成本较高且使用相同的参数重复
记忆化是一种优化技术,用于通过存储昂贵的函数调用的结果并在再次出现相同的输入时重用它们来加速程序。在 Python 中,functools 模块提供了 lru_cache 装饰器,它提供了一种缓存函数结果的简单方法。在函数调用的计算成本较高且使用相同的参数重复调用函数的情况下,此方法特别有用。
要使用 lru_cache,您只需用 @lru_cache 修饰函数即可。下面是一个基本示例:
from functools import lru_cache@lru_cache(maxsize=None)def expensive_function(n): # Simulate an expensive computation print(f"Computing expensive_function({n})") return n * n# Call the function with the same argument multiple timesprint(expensive_function(4)) # Output: Computing expensive_function(4) 16print(expensive_function(4)) # Output: 16 (result is cached, no computation)在此示例中,使用参数 4 调用 expensive_function 两次。第一次调用计算结果,而第二次调用从缓存中检索结果,从而避免计算。
斐波那契数列是一个典型的例子,其中记忆化可以显着提高性能。如果没有记忆化,朴素的递归方法具有指数级的时间复杂性。使用 lru_cache,我们可以将其优化为线性时间复杂度。
from functools import lru_cache@lru_cache(maxsize=None)def fibonacci(n): if n在此示例中,fibonacci 函数通过缓存每次计算的结果来有效地计算 Fibonacci 数列。
lru_cache 还可以处理带有关键字参数的函数。下面是一个示例:
from functools import lru_cache@lru_cache(maxsize=None)def greet(name, greeting="Hello"): print(f"Generating greeting for {name}") return f"{greeting}, {name}!"# Call the function with the same argumentsprint(greet("Alice")) # Output: Generating greeting for Alice Hello, Alice!print(greet("Alice")) # Output: Hello, Alice! (result is takan from the cache)print(greet("Alice", greeting="Hi")) # Output: Generating greeting for Alice Hi, Alice!print(greet("Alice", greeting="Hi")) # Output: Hi, Alice! (result is takan from the cache)有时,您可能希望清除缓存,例如,如果缓存的数据变得无效,或者您想要对更新的数据运行代码。您可以使用 cache_clear 方法执行此操作:
# Clear the cachefibonacci.cache_clearfunctools 模块中的 lru_cache 装饰器是 Python 中记忆化的强大工具。通过缓存昂贵的函数调用的结果,lru_cache可以显著提高程序的性能。它在递归算法和使用相同的参数重复调用函数的方案中特别有用
来源:自由坦荡的湖泊AI