-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlru.py
33 lines (29 loc) · 916 Bytes
/
lru.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
class LRUCache:
"""A cache that implments the LRU policy and uses an injected backing store
Members:
size: int
keys: list
cache : Dict or MemCache
"""
def __init__(self, size, cache):
self.size = size
self.keys = []
self.cache = cache
def get(self, key):
if key in self.keys:
i = self.keys.index(key)
del self.keys[i]
self.keys.append(key)
return self.cache.get(key)
else:
return None
def put(self, key, value):
if key in self.keys:
i = self.keys.index(key)
del self.keys[i]
else:
if len(self.keys) == self.size:
self.cache.remove(self.keys[0])
del self.keys[0]
self.keys.append(key)
self.cache.put(key, value)