hashq2.py

#! /usr/bin/python3
# ==================================================================
# From: www.youtube.com/watch?v=o9pEzgHorH0
#       Stop Writing Classes (YouTube)
# ==================================================================
#
# heapq module provides an implementation of the heap queue
# algorithm, also known as the priority queue algorithm.
#
# See: https://docs.python.org/3/library/heapq.html
#
# ==================================================================

import heapq 

class Heap(object):

    def __init__(self, data=None, key=lambda x: x[0]):
        self.heap = data or []
        heapq.heapify(self.heap)
        self.key = key

    def pushleft(self, item):
        if self.key:
            item = (self.key(item), item)
        ##heapq.pushleft(self.heap, item)
        heapq.heappush(self.heap, item)

    def popleft(self):
        ##return heapq.popleft(self.heap)[1]
        return heapq.heappop(self.heap)[1]

# ------------------------------------------------------------------
# main
# ------------------------------------------------------------------

if __name__ == '__main__':

    pq = Heap()

    # ---- list

    pq.pushleft([9,'abc'])
    pq.pushleft([5,'xyz'])
    pq.pushleft([3,'bcd'])
    pq.pushleft([2,'cde'])

    # ---- tuple

    pq.pushleft((19,'abc'))
    pq.pushleft((15,'xyz'))
    pq.pushleft((13,'bcd'))
    pq.pushleft((12,'cde'))

    l = len(pq.heap)               # length of heap
    i = 0                          # iteration index

    ##print('pq len={}'.format(len(pq.heap)))

    while i < l:
        item = pq.popleft()
        print(item)
        i = i + 1

    print('end of pq')