擅长:python、mysql、java
<h2>解决方案</h2>
<p>您可以通过如下方式使用<code>OrderedDict</code>修复现有代码:</p>
<pre><code>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
</code></pre>
<h2>测试一下</h2>
<pre><code>def mysum(a, b):
return a + b
mysum_cached,cache = memoize(mysum, 10)
for i in range(100)
mysum_cached(i, i)
print(cache)
</code></pre>
<p>输出:</p>
<pre><code>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)])
</code></pre>
<p>这个版本的<code>memoize</code>很可能适合您自己的代码。但是,对于生产代码(即其他人必须依赖的代码),您可能应该使用Mark Meyer建议的标准库函数(<code>functools.lru_cache</code>)。你知道吗</p>