在python中缓存函数的最后k个结果

FJ_*_*asi 3 python caching function memoization python-3.x

我想编写一个接受单参数函数 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
Run Code Online (Sandbox Code Playgroud)

我所做的是:

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
Run Code Online (Sandbox Code Playgroud)

该函数从缓存中返回结果,如果缓存中没有,则计算并缓存。但是,我不清楚如何仅缓存 f 的最后 k 个结果?我是新手,任何帮助将不胜感激。

Mar*_*yer 6

您可以只用来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))
Run Code Online (Sandbox Code Playgroud)

结果:

调用函数
4
4
调用函数
6
6
调用函数
8
8
调用函数
4