9/37
Part 2 of 6 · The LRU orderLearn and do
The dict maps each key to its node
With the list in place, the cache class ties it to a dict.
class LRUCache:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("capacity must be at least 1")
self.capacity = capacity
# key -> its node
self.nodes = {}
# oldest is head.next, newest is tail.prev
self.head, self.tail = Node(), Node()
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def _push(self, node):
last = self.tail.prev
last.next, node.prev = node, last
node.next, self.tail.prev = self.tail, node
def get(self, key, default=None):
node = self.nodes.get(key)
if node is None:
return default
# a hit is a use: move it to newest
self._unlink(node)
self._push(node)
return node.value
The dict holds each key's node, so finding a key's place in the order is one lookup. Here is the cache after the trace's first three calls, put("a", 1), put("b", 2) and get("a"):
Key in self.nodes | Its node | Place in the list |
|---|---|---|
| "b" | b 2 | head.next, the oldest use |
| "a" | a 1 | tail.prev, the newest use |
Notice that get writes. Every hit rewrites six pointers, two to unlink and four to push back. That matters the moment two threads share the cache, which comes up in the follow-ups.
The LRUCache in the editor has the same __init__, _unlink and _push as above, and its get returns the right values. A full cache still evicts the wrong key. Fix get.