我想编写一个接受单参数函数f和整数k的函数,并返回一个与f相同的函数,除非它缓存f的最后k个结果.
例如,如果memoize是我们追求的函数,让mem_f = memoize(f,2),那么:
mem_f(arg1) -> f(arg1) is computed and cached
mem_f(arg1) -> f(arg1) is returned from cache
mem_f(arg2) -> f(arg2) is computed and cached
mem_f(arg3) -> f(arg3) is computed and cached, and f(arg1) is evicted
我所做的是:
def memoize(f,k):
cache = dict()
def mem_f(*args):
if args in cache:
return cache[args]
result = f(*args)
cache[args]= result
return result
return mem_f
此函数返回缓存中的结果,如果它不在缓存中,则计算并缓存它.但是,我不清楚如何只缓存f的最后k个结果?我是新手,任何帮助将不胜感激.
最佳答案 您可以使用
functools.lru_cache
来执行缓存.我接受一个maxsize参数来控制它缓存的程度:
from functools import lru_cache
@lru_cache(maxsize=2)
def test(n):
print("calling function")
return n * 2
print(test(2))
print(test(2))
print(test(3))
print(test(3))
print(test(4))
print(test(4))
print(test(2))
结果:
calling function
4
4
calling function
6
6
calling function
8
8
calling function
4