Overview
Build the cache that sits in front of most APIs: keep the most recently used answers, evict the oldest in O(1), and count a read as a use.
- OrderedDict keeps recency order
- move_to_end and popitem(last=False)
- a read counts as a use
Short Course
An LRU cache keeps the n most recently used entries and evicts the oldest.
OrderedDict remembers order, and move_to_end and popitem(last=False)
work in O(1). Trap: reading a key counts as using it.
from collections import OrderedDict
d = OrderedDict(a=1, b=2, c=3)
d.move_to_end("a") # a is now the newest
d.popitem(last=False) # ('b', 2): oldest out
Task
Write a class LRUCache(capacity) with get(key) (the value, or None) and
put(key, value). When it's full, putting a new key evicts the least
recently used one. Reading a key with get or updating it with put
makes it the most recently used.
Test Suites
Pending
Next
Output