How the push method works

2

In the code:

import heapq

class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0
    def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

class Person:

        def __init__(self,name):
            self.name = name

        def __repr__(self):
            return self.name

lista = PriorityQueue()
lista.push(Person('Dener'), 30)
lista.push(Person('Rodrigo'), 25)
lista.push(Person('Lucas'), 22)

I do not quite understand how the method works:

def push(self, item, priority):
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

Could anyone explain?

    
asked by anonymous 20.10.2017 / 01:50

1 answer

0

This method push stores the item in the queue attribute according to priority, from lowest to highest, and stores the amount of array elements in the _index attribute. If you want to better understand how the heapq class works, take a look at this link .

    
07.11.2017 / 14:45