from __future__ import annotations from collections import OrderedDict from typing import Generic, Iterator, Optional, TypeVar K = TypeVar("K") V = TypeVar("V") class LRUCache(Generic[K, V]): """A small LRU cache backed by an OrderedDict.""" 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) -> Optional[V]: """Return a value and mark it as recently used, or None if missing.""" if key not in self._items: return None self._items.move_to_end(key) return self._items[key] 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 delete(self, key: K) -> bool: """Remove a key if present.""" if key not in self._items: return False del self._items[key] return True def items(self) -> Iterator[tuple[K, V]]: """Yield items from least recently used to most recently used.""" return iter(self._items.items()) 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(capacity=2) cache.put("a", 1) cache.put("b", 2) assert list(cache.items()) == [("a", 1), ("b", 2)] assert cache.get("a") == 1 cache.put("c", 3) assert cache.get("b") is None assert list(cache.items()) == [("a", 1), ("c", 3)] def _test_update_refreshes_recency() -> None: cache: LRUCache[str, int] = LRUCache(capacity=2) cache.put("a", 1) cache.put("b", 2) cache.put("a", 10) cache.put("c", 3) assert cache.get("a") == 10 assert cache.get("b") is None assert cache.get("c") == 3 if __name__ == "__main__": _test_eviction() _test_update_refreshes_recency() print("All tests passed.")