-
Notifications
You must be signed in to change notification settings - Fork 309
/
LRU_cache.py
50 lines (38 loc) · 1.16 KB
/
LRU_cache.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
47
48
49
50
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.stack = OrderedDict()
self.capacity = capacity
def get(self, key):
if key in self.stack:
self.stack.move_to_end(key)
return self.stack[key]
else:
return None
def put(self, key, value) -> None:
if key in self.stack:
self.stack[key] = value
self.stack.move_to_end(key)
else:
self.stack[key] = value
if len(self.stack) > self.capacity:
self.stack.popitem(last=False)
def change_capacity(self, capacity):
self.capacity = capacity
for i in range(len(self.stack) - capacity):
self.stack.popitem(last=False)
def delete(self, key):
if key in self.stack:
del self.stack[key]
def keys(self):
return self.stack.keys()
def __len__(self):
return len(self.stack)
def __contains__(self, key):
return key in self.stack
if __name__ == '__main__':
cache = LRUCache(2)
cache.put(0, 1)
cache.put(1, 1)
cache.put(2, 1)
print(0 in cache)