Python Design Patterns - Queues



Queue is a collection of objects, which define a simple data structure following the FIFO (Fast In Fast Out) and the LIFO (Last In First Out) procedures. The insert and delete operations are referred as enqueue and dequeue operations.

Queues do not allow random access to the objects they contain.

Example - How to implement the FIFO procedure?

The following program helps in the implementation of FIFO −

main.py

import queue

q = queue.Queue()

#put items at the end of the queue
for x in range(4):
   q.put("item-" + str(x))

#remove items from the head of the queue
while not q.empty():
   print(q.get())

Output

The above program generates the following output −

item-0
item-1
item-2
item-3

Example - How to implement the LIFO procedure?

The following program helps in the implementation of the LIFO procedure −

import queue

q = queue.LifoQueue()

#add items at the head of the queue
for x in range(4):
   q.put("item-" + str(x))

#remove items from the head of the queue
while not q.empty():
   print(q.get())

Output

The above program generates the following output −

item-3
item-2
item-1
item-0

Example - What is a Priority Queue?

Priority queue is a container data structure that manages a set of records with the ordered keys to provide quick access to the record with smallest or largest key in specified data structure.

How to implement a priority queue?

The implementation of priority queue is as follows −

import queue

class Task(object):
   def __init__(self, priority, name):
      self.priority = priority
      self.name = name
   
   def __lt__(self, other):
      return self.priority > other.priority

q = queue.PriorityQueue()

q.put( Task(100, 'a not agent task') )
q.put( Task(5, 'a highly agent task') )
q.put( Task(10, 'an important task') )

while not q.empty():
   cur_task = q.get()
   print('process task:', cur_task.name)

Output

The above program generates the following output −

process task: a not agent task
process task: an important task
process task: a highly agent task
Advertisements