-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlru_cache.py
More file actions
49 lines (39 loc) · 1.07 KB
/
lru_cache.py
File metadata and controls
49 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
46
47
48
49
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.dict = OrderedDict()
self.current_capacity = capacity
def get(self, key):
"""
:type key: int
:rtype: int
"""
# print('During get of',key,':',self.dict)
if key not in self.dict:
return -1
value = self.dict[key]
del self.dict[key]
self.dict[key] = value
return value
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
"""
# print('during put of ',key,value)
if key in self.dict:
del self.dict[key]
else:
if self.current_capacity > 0:
self.current_capacity -= 1
else:
self.dict.popitem(last = False)
self.dict[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)