PYTHON
Implement a Fixed-Size Circular Buffer with Deque
Create an efficient fixed-size circular buffer or history log using `collections.deque` in Python, perfect for managing recent items with automatic older item eviction.
from collections import deque
# Create a deque with a maximum size of 3
recent_activity = deque(maxlen=3)
print(f"Initial deque: {list(recent_activity)}")
recent_activity.append('User logged in')
print(f"After 1st append: {list(recent_activity)}")
recent_activity.append('Item added to cart')
print(f"After 2nd append: {list(recent_activity)}")
recent_activity.append('Payment processed')
print(f"After 3rd append: {list(recent_activity)}")
# Appending a new item will automatically remove the oldest one
recent_activity.append('User logged out')
print(f"After 4th append (oldest removed): {list(recent_activity)}")
recent_activity.appendleft('Admin action') # Add to the front
print(f"After appendleft: {list(recent_activity)}")
# You can also use it as a queue
print(f"Popping from right: {recent_activity.pop()}")
print(f"Deque after pop: {list(recent_activity)}")
How it works: This code showcases `collections.deque` (double-ended queue) configured with a `maxlen`. When the `deque` reaches its maximum size, adding new elements (using `append` or `appendleft`) automatically removes elements from the opposite end, creating a "circular buffer" or fixed-size history. This is efficient for managing a limited number of most recent items or logs.