Operation of the push method

Asked

Viewed 233 times

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 don’t really understand how the method works:

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

Could someone explain to me?

  • It seems to me that one is missing ) somewhere.

  • I’ve already edited @Lacobus

  • @Lucasmoraes you could explain me if your code runs and you just want a help to understand the method, or the code presents some error

1 answer

0

That method push stores the item in the Queue attribute according to the Priority, from the smallest to the largest, and stores the amount of array elements in the attribute _index. If you want to better understand how the heapq class works, take a look at this link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.