-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRU Cache.py
More file actions
45 lines (39 loc) · 1.07 KB
/
Copy pathLRU Cache.py
File metadata and controls
45 lines (39 loc) · 1.07 KB
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
class LRUCache:
def __init__(self,capacity):
self.size = capacity
self.age = 0
self.dic = {}
def put(self,key,value):
self.age += 1
if len(self.dic) != self.size:
cache = Cache(key,value,self.age)
self.dic[key] = cache
else:
if key in self.dic:
self.dic[key] = Cache(key,value,self.age)
else:
min_cache = min(self.dic,key=lambda x:self.dic[x].age)
self.dic.pop(min_cache)
self.dic[key] = Cache(key,value,self.age)
def get(self, key):
if key in self.dic:
value = self.dic[key].value
self.put(key,value)
return value
else:
return -1
class Cache:
def __init__(self,key,value,age):
self.key=key
self.value=value
self.age = age
cache = LRUCache(2)
print([cache.put(1,1),
cache.put(2,2),
cache.get(1),
cache.put(3,3),
cache.get(2),
cache.put(4,4),
cache.get(1),
cache.get(3),
cache.get(4)])