AI-Assisted Coding Lab · Add Expiry to an LRU Cache

45:00left of 45:00

Add Expiry to an LRU Cache

The pricing service caches prices in an LRU cache, and product wants entries to go stale after a TTL. The README has the rules. Build it with the assistant: accept, edit, or reject each suggestion, and keep the tests green.

lru.py1 of 3

Files

lru.py

Python · Editable
import time
from collections import OrderedDict
class LRUCache:
"""Least recently used cache. Entries expire ttl_s seconds after they are written."""
def __init__(self, capacity, ttl_s, clock=time.monotonic):
if capacity < 1:
raise ValueError("capacity must be at least 1")
self.capacity = capacity
self.ttl_s = ttl_s
self.clock = clock
self.data = OrderedDict() # key -> (value, expires_at)
def get(self, key):
if key not in self.data:
return None
value, expires_at = self.data[key]
self.data.move_to_end(key)
return value
def put(self, key, value):
self.data[key] = (value, self.clock() + self.ttl_s)
self.data.move_to_end(key)
if len(self.data) > self.capacity:
self.data.popitem(last=False)
def __len__(self):
return len(self.data)

Test Output

No runs yet.

Assistant

Scripted
  1. Send the first prompt to start.

Next Prompt

Reject a ttl_s that isn't positive, the way capacity is checked.