← run

py-04-lru-ttl-cache

1.000
8/8 tests· data-structures

Proposed solution

```python
import time
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int, ttl: float, now=time.monotonic):
        self.capacity = capacity
        self.ttl = ttl
        self.now = now
        self.cache = OrderedDict()

    def get(self, key):
        if key in self.cache:
            value, timestamp = self.cache[key]
            if self.now() - timestamp < self.ttl:
                self.cache.move_to_end(key)
                return value
            else:
                del self.cache[key]
        return None

    def put(self, key, value):
        if key in self.cache:
            del self.cache[key]
        elif len(self.cache) >= self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = (value, self.now())

    def __len__(self) -> int:
        return sum(1 for key, (_, timestamp) in self.cache.items() if self.now() - timestamp < self.ttl)
```

Test output (stdout)

........                                                                 [100%]
8 passed in 0.02s
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.