from collections import deque class RecentItemsCache: """A fixed-size cache for storing the most recent items/actions. When the cache is full, adding a new item removes the oldest one. """ def __init__(self, max_size): if not isinstance(max_size, int) or max_size <= 0: raise ValueError("max_size must be a positive integer.") self.max_size = max_size self._items = deque(maxlen=max_size) def add_item(self, item): """Adds an item to the cache. If the item is already present, it's moved to the most recent position. """ if item in self._items: self._items.remove(item) # Remove existing to re-add at end self._items.append(item) def get_items(self): """Returns the items in the cache from oldest to most recent. """ return list(self._items) def get_most_recent(self, n=1): """Returns the 'n' most recent items. 'n' cannot exceed cache size. """ if n > len(self._items): n = len(self._items) # Adjust n if it's larger than current size return list(self._items)[-n:] # Return a slice from the end def __len__(self): return len(self._items) def __repr__(self): return f"RecentItemsCache({list(self._items)})" # Example Usage: user_history = RecentItemsCache(max_size=3) user_history.add_item('/products/1') user_history.add_item('/cart') user_history.add_item('/products/2') print(f"Current history: {user_history.get_items()}") # ['/products/1', '/cart', '/products/2'] user_history.add_item('/checkout') # '/products/1' is pushed out print(f"Current history: {user_history.get_items()}") # ['/cart', '/products/2', '/checkout'] user_history.add_item('/products/2') # '/products/2' is moved to end print(f"Current history: {user_history.get_items()}") # ['/cart', '/checkout', '/products/2'] print(f"Most recent item: {user_history.get_most_recent(1)}") # ['/products/2'] print(f"Two most recent items: {user_history.get_most_recent(2)}") # ['/checkout', '/products/2']