擅长:python、mysql、java
<p>扩展Mark Meyer的优秀建议,下面是使用<code>lru_cache</code>和问题术语的解决方案:</p>
<pre><code>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()
</code></pre>
<p>结果:</p>
<pre><code>Called with 3, 4
Answer: 12
Answer: 12
Called with 3, 7
Answer: 21
Called with 3, 8
Answer: 24
</code></pre>