Spaces:
Sleeping
Sleeping
from collections import OrderedDict | |
class CacheManager: | |
"""Simple cache manager with basic operations and LRU eviction.""" | |
def __init__(self, max_size=100): | |
"""Initialize cache with maximum size.""" | |
self.max_size = max_size | |
self.cache = OrderedDict() | |
def set(self, key, value): | |
"""Set a key-value pair in cache.""" | |
# If key exists, remove it first | |
if key in self.cache: | |
del self.cache[key] | |
# If cache is full, remove oldest item | |
if len(self.cache) >= self.max_size: | |
self.cache.popitem(last=False) # Remove first (oldest) item | |
# Add new item | |
self.cache[key] = value | |
def get(self, key): | |
"""Get value by key. Returns None if not found.""" | |
if key in self.cache: | |
# Move to end (mark as recently used) | |
value = self.cache.pop(key) | |
self.cache[key] = value | |
return value | |
return None | |
def delete(self, key): | |
"""Delete a key from cache. Returns True if deleted, False if not found.""" | |
if key in self.cache: | |
del self.cache[key] | |
return True | |
return False | |
def clear(self): | |
"""Clear all items from cache.""" | |
self.cache.clear() | |
def size(self): | |
"""Get current cache size.""" | |
return len(self.cache) | |