priority queue python code example

Example 1: queue python

from queue import Queue

q = Queue()

q.size() # returns the current lenght of queue
q.empty() # returns True if empty, False otherwise
q.put(item) 
q.get()

Example 2: python priority queue

from queue import PriorityQueue

class PqElement(object):
    def __init__(self, value: int):
        self.val = value

    #Custom Compare Function (less than or equsal)
    def __lt__(self, other):
        """self < obj."""
        return self.val > other.val

    #Print each element function
    def __repr__(self):
        return f'PQE:{self.val}'

#Usage-
pq = PriorityQueue()
pq.put(PqElement(v))       #Add Item      - O(Log(n))
topValue = pq.get()        #Pop top item  - O(1)
topValue = pq.queue[0].val #Get top value - O(1)

Example 3: python heapq

>>> import heapq
>>> heap = []
>>> heapq.heappush(heap, (5, 'write code'))
>>> heapq.heappush(heap, (7, 'release product'))
>>> heapq.heappush(heap, (1, 'write spec'))
>>> heapq.heappush(heap, (3, 'create tests'))
>>> heapq.heappop(heap)#pops smallest
(1, 'write spec')
>>> heapq.nlargest(2,heap)#displays n largest values without popping
[(7, 'release product'),(5, 'write code')]
>>> heapq.nsmallest(2,heap)#displays n smallest values without popping
[(3, 'create tests'),(5, 'write code')]
>>> heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapq.heapify(heap)#converts a list to heap
>>> heap
[0, 1, 2, 6, 3, 5, 4, 7, 8, 9]
>>> def heapsort(iterable):
...     h = []
...     for value in iterable:
...         heappush(h, value)
...     return [heappop(h) for i in range(len(h))]
...
>>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 4: python priority queue

class PriorityQueueSet(object):

    """
    Combined priority queue and set data structure.

    Acts like a priority queue, except that its items are guaranteed to be
    unique. Provides O(1) membership test, O(log N) insertion and O(log N)
    removal of the smallest item.

    Important: the items of this data structure must be both comparable and
    hashable (i.e. must implement __cmp__ and __hash__). This is true of
    Python's built-in objects, but you should implement those methods if you
    want to use the data structure for custom objects.
    """

    def __init__(self, items=[]):
        """
        Create a new PriorityQueueSet.

        Arguments:
            items (list): An initial item list - it can be unsorted and
                non-unique. The data structure will be created in O(N).
        """
        self.set = dict((item, True) for item in items)
        self.heap = self.set.keys()
        heapq.heapify(self.heap)

    def has_item(self, item):
        """Check if ``item`` exists in the queue."""
        return item in self.set

    def pop_smallest(self):
        """Remove and return the smallest item from the queue."""
        smallest = heapq.heappop(self.heap)
        del self.set[smallest]
        return smallest

    def add(self, item):
        """Add ``item`` to the queue if doesn't already exist."""
        if item not in self.set:
            self.set[item] = True
            heapq.heappush(self.heap, item)