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

2024-04-28 21:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,它接受一个单参数函数f和一个整数k,并返回一个与f行为相同的函数,只是它缓存f的最后k个结果

例如,如果memoize是我们要找的函数,让mem\u 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个结果?我是新手,任何帮助都将不胜感激。你知道吗


Tags: and函数cachereturnisdefargsresult
3条回答

扩展Mark Meyer的优秀建议,下面是使用lru_cache和问题术语的解决方案:

from functools import lru_cache


def memoize(f, k):
    mem_f = lru_cache(maxsize=k)(f)
    return mem_f


def multiply(a, b):
    print("Called with {}, {}".format(a, b))
    return a * b


def main():
    memo_multiply = memoize(multiply, 2)
    print("Answer: {}".format(memo_multiply(3, 4)))
    print("Answer: {}".format(memo_multiply(3, 4)))
    print("Answer: {}".format(memo_multiply(3, 7)))
    print("Answer: {}".format(memo_multiply(3, 8)))


if __name__ == "__main__":
    main()

结果:

Called with 3, 4
Answer: 12
Answer: 12
Called with 3, 7
Answer: 21
Called with 3, 8
Answer: 24

解决方案

您可以通过如下方式使用OrderedDict修复现有代码:

from collections import OrderedDict

def memoize(f, k):
    cache = OrderedDict()

    def mem_f(*args):
        if args in cache:
            return cache[args]
        result = f(*args)
        if len(cache) >= k:
            cache.popitem(last=False)
        cache[args]= result
        return result 
    return mem_f,cache

测试一下

def mysum(a, b):
    return a + b

mysum_cached,cache = memoize(mysum, 10)
for i in range(100)
    mysum_cached(i, i)

print(cache)

输出:

OrderedDict([((90, 90), 180), ((91, 91), 182), ((92, 92), 184), ((93, 93), 186), ((94, 94), 188), ((95, 95), 190), ((96, 96), 192), ((97, 97), 194), ((98, 98), 196), ((99, 99), 198)])

这个版本的memoize很可能适合您自己的代码。但是,对于生产代码(即其他人必须依赖的代码),您可能应该使用Mark Meyer建议的标准库函数(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

相关问题 更多 >