Queue in Python - Part 3

Prioritize your queue A PriorityQueue is a type of queue imported from the module with the same name. It uses sort order to decide what to retrieve from it first (your object must have a way of comparing its instances): import queue class Rezha(object): def __init__(self, priority): self.priority = priority def __lt__(self, other): return self.priority > other.priority q = queue.PriorityQueue() q.put(Rezha(11)) q.put(Rezha(55)) q.put(Rezha(100)) while not q.empty(): print(q.get().priority) # output is 100 / 55 / 11 Having defined the __lt__ method, our PriorityQueue knows now how to sort elements of type Rezha....

December 26, 2016 · 1 min · Rezha Julio

Queue in Python - Part 2

Double ended queues with deque The deque class in the collections module makes it easy to create deques or double ended queues. Deques allow you to append and delete elements from both ends more efficiently than in lists. Import the module: from collections import deque Instantiate deque: d = deque() Append to right and left: d.append("b") d.appendleft("a") print(d) # output is: deque(['a', 'b']) In the same fashion, elements can be deleted (popped) :...

November 2, 2016 · 1 min · Rezha Julio

Queue in Python - Part 1

Best way to implement a simple queue A simple list can be easily used and implemented as a queue abstract data structure. A queue implies the first-in, first-out principle. However, this approach will prove inefficient because inserts and pops from the beginning of a list are slow (all elements need shifting by one). It’s recommended to implement queues using the collections.deque module as it was designed with fast appends and pops from both ends....

November 2, 2016 · 1 min · Rezha Julio