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):
12
12
return f (n - 1 ) + f (n - 2 ) # 由于涉及到重复计算,这个递归函数在 n 大了以后会非常慢。 O(2^n)
13
13
14
14
15
+ """
16
+ 下边就来写一个缓存装饰器来优化它。传统方法是用个数组记录之前计算过的值,但是这种方式不够 Pythonic
17
+ """
18
+
19
+
15
20
def cache (func ):
16
21
"""先引入一个简单的装饰器缓存,其实原理很简单,就是内部用一个字典缓存已经计算过的结果"""
17
22
store = {}
@@ -69,18 +74,18 @@ def __init__(self, capacity=128):
69
74
# OrderedDict 有两个重要的函数用来实现 LRU,一个是 move_to_end,一个是 popitem,请自己看文档
70
75
self .od = OrderedDict ()
71
76
72
- def get (self , key ):
77
+ def get (self , key , default = None ):
78
+ val = self .od .get (key , default ) # 如果没有返回 default,保持 dict 语义
73
79
self .od .move_to_end (key ) # 每次访问就把key 放到最后表示最新访问
74
- return self . od [ key ]
80
+ return val
75
81
76
82
def add_or_update (self , key , value ):
77
83
if key in self .od : # update
78
84
self .od [key ] = value
79
85
self .od .move_to_end (key )
80
86
else : # insert
81
87
self .od [key ] = value
82
- if len (self .od ) > self .capacity :
83
- print ("FULL ||||||||||||||||" )
88
+ if len (self .od ) > self .capacity : # full
84
89
self .od .popitem (last = False )
85
90
86
91
def __call__ (self , func ):
You can’t perform that action at this time.
0 commit comments