Repository navigation
Expand file tree
/
Copy pathlru_cache.py
More file actions
62 lines (58 loc) · 2.34 KB
/
Copy pathlru_cache.py
File metadata and controls
62 lines (58 loc) · 2.34 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
50
51
52
53
54
55
56
57
58
59
60
61
62
import sys
sys.path.append('../doubly_linked_list')
from doubly_linked_list import DoublyLinkedList
class LRUCache:
"""
Our LRUCache class keeps track of the max number of nodes it
can hold, the current number of nodes it is holding, a doubly-
linked list that holds the key-value entries in the correct
order, as well as a storage dict that provides fast access
to every node stored in the cache.
"""
def __init__(self, limit=10):
self.limit = limit
self.size = 0
# self.order = # [] or DLL? what does a node store? The KEY! Answer: DLL because it updates frequently
self.storage = {}
self.order = DoublyLinkedList()
"""
Retrieves the value associated with the given key. Also
needs to move the key-value pair to the end of the order
such that the pair is considered most-recently used.
Returns the value associated with the key or None if the
key-value pair doesn't exist in the cache.
"""
def get(self, key):
if key in self.storage:
# Find the key in order and move to the front
node = self.storage[key]
self.order.move_to_front(node)
return node.value[1]
else:
return None
"""
Adds the given key-value pair to the cache. The newly-
added pair should be considered the most-recently used
entry in the cache. If the cache is already at max capacity
before this entry is added, then the oldest entry in the
cache needs to be removed to make room. Additionally, in the
case that the key already exists in the cache, we simply
want to overwrite the old value associated with the key with
the newly-specified value.
"""
def set(self, key, value):
# update node value if node already exists
if key in self.storage:
node = self.storage[key]
node.value = (key, value)
self.order.move_to_front(node)
return
# Get the oldest node and remove to make room, either tail or head depending on DLL setup:
if self.size == self.limit:
del self.storage[self.order.tail.value[0]]
self.order.remove_from_tail()
self.size -= 1
# add the node to storage
self.order.add_to_head( (key,value) )
self.storage[key] = self.order.head
self.size +=1