什么是回忆录,我如何在Python中使用它?我刚开始Python我不知道回忆录以及如何使用它。另外,可以给我一个简化的例子吗?
3 回答
精慕HU
TA贡献1845条经验 获得超8个赞
factorial_memo = {}def factorial(k): if k < 2: return 1 if k not in factorial_memo: factorial_memo[k] = k * factorial(k-1) return factorial_memo[k]
class Memoize: def __init__(self, f): self.f = f self.memo = {} def __call__(self, *args): if not args in self.memo: self.memo[args] = self.f(*args) #Warning: You may wish to do a deepcopy here if returning objects return self.memo[args]
def factorial(k): if k < 2: return 1 return k * factorial(k - 1)factorial = Memoize(factorial)
@Memoizedef factorial(k): if k < 2: return 1 return k * factorial(k - 1)
memoized
Memoize
慕神8447489
TA贡献1780条经验 获得超1个赞
functools.lru_cache
maxsize
None
import functools@functools.lru_cache(maxsize=None)def fib(num): if num < 2: return num else: return fib(num-1) + fib(num-2)
fib(36)
lru_cache
添加回答
举报
0/150
提交
取消