Code :
Explanation:
๐น 1. Importing deque
from collections import deque
✅ Explanation
deque means Double Ended Queue.
It allows insertion and deletion from both ends efficiently.
Here we'll use a special feature called maxlen.
Think of it like a train with only 4 seats.
Train Capacity = 4
๐ [ _ | _ | _ | _ ]
No matter how many passengers come, only 4 passengers can stay.
๐น 2. Creating a Fixed-Size Queue
d = deque(maxlen=4)
✅ Explanation
A deque is created with a maximum capacity of 4.
Current state:
Capacity = 4
[]
Important rule:
If queue becomes full,
new element enters,
oldest element automatically leaves.
Unlike a normal list, you never get an overflow error.
๐น 3. Starting the Loop
for i in range(6):
✅ Explanation
range(6) generates:
0
1
2
3
4
5
Python will execute the loop 6 times.
๐น 4. First Iteration (i = 0)
d.append(0)
Queue before:
[]
Queue after:
[0]
Seats occupied:
๐ [0 | _ | _ | _]
Still space available.
๐น 5. Second Iteration (i = 1)
d.append(1)
Queue:
[0,1]
Visual:
๐ [0 | 1 | _ | _]
Still not full.
๐น 6. Third Iteration (i = 2)
d.append(2)
Queue:
[0,1,2]
Visual:
๐ [0 | 1 | 2 | _]
One seat remains.
๐น 7. Fourth Iteration (i = 3)
d.append(3)
Queue becomes:
[0,1,2,3]
Visual:
๐ [0 | 1 | 2 | 3]
Now the queue is completely full.
Capacity:
4 / 4
๐น 8. Fifth Iteration (i = 4)
d.append(4)
Here's the interesting part.
Current queue:
[0,1,2,3]
But there is no empty seat.
So Python automatically removes the oldest element.
Oldest element:
0
After removing 0:
[1,2,3]
Now 4 is inserted.
Final queue:
[1,2,3,4]
Visual:
Before
๐ [0 | 1 | 2 | 3]
Passenger 4 arrives
↓
Passenger 0 leaves automatically
↓
๐ [1 | 2 | 3 | 4]
This behavior is called a Sliding Window.
๐น 9. Sixth Iteration (i = 5)
d.append(5)
Current queue:
[1,2,3,4]
Again queue is full.
Oldest passenger:
1
Leaves automatically.
New passenger:
5
enters.
Final queue:
[2,3,4,5]
Visual:
Before
๐ [1 | 2 | 3 | 4]
Passenger 5 arrives
↓
Passenger 1 leaves
↓
๐ [2 | 3 | 4 | 5]
๐น 10. Printing the Queue
print(list(d))
✅ Explanation
The deque is converted into a list.
Final output:
[2, 3, 4, 5]
๐ฏ Final Output
[2, 3, 4, 5]

0 Comments:
Post a Comment