File tree Expand file tree Collapse file tree 1 file changed +9
-4
lines changed Expand file tree Collapse file tree 1 file changed +9
-4
lines changed Original file line number Diff line number Diff line change @@ -12,6 +12,11 @@ def fib(n):
1212 return f (n - 1 ) + f (n - 2 ) # 由于涉及到重复计算,这个递归函数在 n 大了以后会非常慢。 O(2^n)
1313
1414
15+ """
16+ 下边就来写一个缓存装饰器来优化它。传统方法是用个数组记录之前计算过的值,但是这种方式不够 Pythonic
17+ """
18+
19+
1520def cache (func ):
1621 """先引入一个简单的装饰器缓存,其实原理很简单,就是内部用一个字典缓存已经计算过的结果"""
1722 store = {}
@@ -69,18 +74,18 @@ def __init__(self, capacity=128):
6974 # OrderedDict 有两个重要的函数用来实现 LRU,一个是 move_to_end,一个是 popitem,请自己看文档
7075 self .od = OrderedDict ()
7176
72- def get (self , key ):
77+ def get (self , key , default = None ):
78+ val = self .od .get (key , default ) # 如果没有返回 default,保持 dict 语义
7379 self .od .move_to_end (key ) # 每次访问就把key 放到最后表示最新访问
74- return self . od [ key ]
80+ return val
7581
7682 def add_or_update (self , key , value ):
7783 if key in self .od : # update
7884 self .od [key ] = value
7985 self .od .move_to_end (key )
8086 else : # insert
8187 self .od [key ] = value
82- if len (self .od ) > self .capacity :
83- print ("FULL ||||||||||||||||" )
88+ if len (self .od ) > self .capacity : # full
8489 self .od .popitem (last = False )
8590
8691 def __call__ (self , func ):
You can’t perform that action at this time.
0 commit comments