def__contains__(self, key): return key in self._map
我们使用装饰器来使用LRUCache。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import functools
deflru_cache(maxsize=100): _cache = LRUCache(maxsize) defcache(func): @functools.wraps(func) defwrapper(key): if key in _cache: return _cache[key] value = func(key) _cache[key] = value return value return wrapper return cache
deffib(n): if n < 0: raise ValueError("n must be zero or positive") if n in (0, 1): return1 return fib(n-1) + fib(n-2)
@lru_cache(maxsize=1000) deffib_with_lru(n): if n < 0: raise ValueError("n must be zero or positive") if n in (0, 1): return1 return fib(n-1) + fib(n-2)
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import time
defmain(): start = time.time() fib(30) end = time.time() print(fib.__name__, 'elapsed time is {}'.format(end-start)) start = time.time() fib_with_lru(30) end = time.time() print(fib_with_lru.__name__, 'elapsed time is {}'.format(end-start))
if __name__ == '__main__': main()
结果如下
1 2
fib elapsed time is 0.6846170425415039 fib_with_lru elapsed time is 0.0010001659393310547