write me a code for least recent used cache
- User
write me a code for least recent used cache
Assistant
Here's an example implementation of a least recent used (LRU) cache in Python:
class LRUCache: def __init__(self, capacity): self.capacity = capacity self.cache = {} self.head = 0 self.tail = 0 def __getitem__(self, key): if key in self.cache: self.remove(key) self.add(key) return self.cache[key] def __setitem__(self, key, value): if len(self.cache) == self.capacity: self.remove(self.head) self.cache[key] = value self.add(key) def add(self, key): if self.head == self.tail: self.head = (self.head + 1) % self.capacity self.cache[key] = self.data[self.head] self.data[self.head] = key self.head = (self.head + 1) % self.capacity def remove(self, key): if key in self.cache: self.data[self.cache[key]] = None if key in self.cache: self.cache.pop(key) self.head = (self.head + 1) % self.capacity else: self.tail = (self.tail - 1) % self.capacity
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.