Untitled
from in_memory_db import InMemoryDB class InMemoryDBImpl(InMemoryDB): def __init__(self): self.db = {} self.modification_counts = {} # To track the number of modifications def set_or_inc(self, key: str, field: str, value: int) -> int: if key not in self.db: self.db[key] = {} self.modification_counts[key] = 0 if field in self.db[key]: self.db[key][field] += value else: self.db[key][field] = value # Increment the modification count whenever a field is set or incremented self.modification_counts[key] += 1 return self.db[key][field] def get(self, key: str, field: str) -> int | None: if key in self.db and field in self.db[key]: return self.db[key][field] return None def delete(self, key: str, field: str) -> bool: if key in self.db and field in self.db[key]: del self.db[key][field] # Increment the modification count whenever a field is deleted self.modification_counts[key] += 1 if not self.db[key]: # If the record has no fields left del self.db[key] del self.modification_counts[key] return True return False def top_n_keys(self, n: int) -> list[str]: sorted_keys = sorted( self.modification_counts.items(), key=lambda item: (-item[1], item[0]) # Sort by modification count desc, then by key name asc ) return [f"{key}({count})" for key, count in sorted_keys[:n]]
Leave a Comment