← 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 not in self.cache:
            return None
            
        # Check if expired
        value, timestamp = self.cache[key]
        if self.now() - timestamp >= self.ttl:
            del self.cache[key]
            return None
            
        # Move to end (mark as recently used)
        self.cache.move_to_end(key)
        return value
        
    def put(self, key, value):
        # Check if key exists
        if key in self.cache:
            # Update existing entry
            _, timestamp = self.cache[key]
            self.cache[key] = (value, self.now())
            self.cache.move_to_end(key)
        else:
            # Insert new entry
            self.cache[key] = (value, self.now())
            
            # Check if we need to evict
            if len(self.cache) > self.capacity:
                # Remove least recently used (first item in OrderedDict)
                self.cache.popitem(last=False)
                
    def __len__(self) -> int:
        # Count live entries (non-expired)
        current_time = self.now()
        count = 0
        
        for value, timestamp in self.cache.values():
            if current_time - timestamp < self.ttl:
                count += 1
                
        return count
```

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.