from collections import OrderedDict from typing import Generic, TypeVar K = TypeVar("K") V = TypeVar("V") class LRUCache(Generic[K, V]): def __init__(self, capacity: int) -> None: if capacity <= 0: raise ValueError("capacity must be positive") self.capacity = capacity self._items: OrderedDict[K, V] = OrderedDict() def get(self, key: K) -> V: """Return a value and mark its key as recently used.""" value = self._items[key] self._items.move_to_end(key) return value def put(self, key: K, value: V) -> None: """Insert or update a value, evicting the least-recently used item.""" if key in self._items: self._items.move_to_end(key) self._items[key] = value if len(self._items) > self.capacity: self._items.popitem(last=False) def __contains__(self, key: object) -> bool: return key in self._items def __len__(self) -> int: return len(self._items) def test_eviction() -> None: cache: LRUCache[str, int] = LRUCache(2) cache.put("a", 1) cache.put("b", 2) cache.get("a") # "b" is now least recently used. cache.put("c", 3) assert "a" in cache assert "b" not in cache assert cache.get("c") == 3 def test_update() -> None: cache: LRUCache[str, int] = LRUCache(2) cache.put("a", 1) cache.put("b", 2) cache.put("a", 10) # Updating also refreshes recency. cache.put("c", 3) assert cache.get("a") == 10 assert "b" not in cache assert len(cache) == 2 def main() -> None: test_eviction() test_update() print("All tests passed.") if __name__ == "__main__": main()