萧十郎
解决方案您可以使用以下方法修复您拥有的代码OrderedDict:from collections import OrderedDictdef 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 + bmysum_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可能适用于您自己的代码。但是,对于生产代码(即其他人必须依赖的代码),您可能应该使用functools.lru_cacheMark Meyer 建议的标准库函数 ( )。
一只名叫tom的猫
扩展 Mark Meyer 的绝妙建议,以下是解决方案的使用方式lru_cache和问题的术语:from functools import lru_cachedef memoize(f, k): mem_f = lru_cache(maxsize=k)(f) return mem_fdef multiply(a, b): print("Called with {}, {}".format(a, b)) return a * bdef 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, 4Answer: 12Answer: 12Called with 3, 7Answer: 21Called with 3, 8Answer: 24