Python 3D Academyবাংলা

Queues & Deques in Python

Chapter 40: Queues & Deques

4 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. First in, first out: queues and collections.deque

    A queue adds items at the back and removes them from the front: the first item in is the first item out (FIFO, first in, first out).

  2. Building a queue: the ring buffer

    Keep a list of exactly capacity slots, a head index for the front and a size; join at (head + size) % capacity and leave from head, moving it on with % capacity, so the indexes wrap round and nothing ever shifts.

  3. The monotonic deque: the maximum of every window

    Keep a deque of the positions in the window that could still be its maximum, their numbers falling from front to back; a new number first removes every smaller-or-equal number from the back, joins the back, and the front leaves once it falls out of the window: the front is always the window's maximum.

  4. Queues in simulations: taking turns, and a first look at BFS

    In a simulation, a queue holds whatever is waiting its turn; each step takes the front, does one piece of work, and puts it back at the end if there is more to do.