forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 1
/
problem_052.py
66 lines (56 loc) · 1.73 KB
/
problem_052.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRU:
def __init__(self, cache_limit):
self.cache_limit = cache_limit
self.cache_contents = dict()
self.head = Node(None, None)
self.tail = Node(None, None)
self.head.next = self.tail
self.tail.prev = self.head
def _remove(self, node):
prev_node = node.prev
next_node = node.next
prev_node.next = next_node
next_node.prev = prev_node
def _add(self, node):
prev_node = self.tail.prev
node.next = self.tail
node.prev = prev_node
prev_node.next = node
self.tail.prev = node
def set_value(self, key, value):
if key in self.cache_contents:
node = self.cache_contents[key]
self._remove(node)
node = Node(key, value)
self._add(node)
self.cache_contents[key] = node
if len(self.cache_contents) > self.cache_limit:
node_to_delete = self.head.next
self._remove(node_to_delete)
del self.cache_contents[node_to_delete.key]
def get_value(self, key):
if key in self.cache_contents:
node = self.cache_contents[key]
self._remove(node)
self._add(node)
return node.value
return None
lru = LRU(cache_limit=3)
assert not lru.get_value("a")
lru.set_value("a", 1)
assert lru.get_value("a") == 1
lru.set_value("b", 2)
lru.set_value("c", 3)
lru.set_value("d", 4)
lru.set_value("e", 5)
lru.set_value("a", 1)
assert lru.get_value("a") == 1
assert not lru.get_value("b")
assert lru.get_value("e") == 5
assert not lru.get_value("c")