-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathlru_allone.py
47 lines (43 loc) · 1.42 KB
/
lru_allone.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
''' mbinary
#########################################################################
# File : lru_allone.py
# Author: mbinary
# Mail: [email protected]
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2019-05-23 23:50
# Description:
#########################################################################
'''
from allOne import allOne
'''In this implementation, the lru doesn't use some funcs of allOne,
such as dec,addDecNode
'''
class lru:
def __init__(self, capacity):
self.capacity = capacity
self.allOne = allOne()
self.data = {}
def get(self,key):
if key in self.data:
self.allOne.move_to_end(key)
return self.data[key]
return -1
def put(self,key,value):
if key not in self.data:
if len(self.data)==self.capacity:
k = self.allOne.delMinKey()
if k in self.data:
del self.data[k]
self.data[key]=value
self.allOne.append(key)
else:
self.data[key]=value
self.allOne.move_to_end(key)
if __name__ == '__main__':
ops = ["put","put","get","put","get","put","get","get","get"]
data = [[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
obj = lru(2)
operate = {'get':obj.get,'put':obj.put}
for op, args in zip(ops,data):
print(f'{op}({args}): {operate[op](*args)}\n{obj.data}\n')