PYTHON
Implement a Fixed-Size Queue with Deque
Utilize Python's `collections.deque` to create an efficient, fixed-size queue, ideal for maintaining a history of the last N items or implementing a sliding window for data analysis.
from collections import deque
def create_fixed_size_history(max_items):
"""Creates a deque (double-ended queue) with a fixed maximum size."""
return deque(maxlen=max_items)
# Example Usage:
recent_actions = create_fixed_size_history(3)
recent_actions.append("User logged in")
recent_actions.append("Viewed product page")
recent_actions.append("Added item to cart")
# print(list(recent_actions)) # Current history: 3 items
# Expected output: ['User logged in', 'Viewed product page', 'Added item to cart']
recent_actions.append("Completed checkout") # 'User logged in' is automatically removed
# print(list(recent_actions)) # History now only contains the 3 most recent actions
# Expected output: ['Viewed product page', 'Added item to cart', 'Completed checkout']
recent_actions.appendleft("Error occurred") # Can also add to the left
# print(list(recent_actions))
# Expected output: ['Error occurred', 'Viewed product page', 'Added item to cart']
How it works: The `collections.deque` (double-ended queue) is a powerful data structure that supports efficient appending and popping from both ends. When initialized with the `maxlen` argument, it becomes a fixed-size queue. Once the deque reaches its maximum size, adding a new item to either end will automatically remove an item from the opposite end, maintaining the fixed size. This is perfect for use cases like storing a history of the last N events, implementing a simple cache, or managing a sliding window of data.