In this simple python tutorial, we learned to implement a priority queue in Python using the queue.PriorityQueue class, heapq and bisect modules with examples. Let’s see an example of how to use the above-created priority queue. import bisectīisect.insort(self.queue, (priority, data)) Since pairs are compared lexicographically, this means that data will be placed in increasing order of priority. Here, we insert the pair (priority, data). The function inserts the second argument in the list so that the list remains sorted in logarithmic (O(log( N))) time. Its insort() method is called with a first argument that is a currently sorted list and an arbitrary second argument. The module is called bisect because it uses a basic bisection algorithm to do its work. The bisect module, from the standard Python library, is very handy for maintaining a sorted list without having to sort the list after each insertion. Heapq.heappush(self._queue, (-priority, self._index, item)) The following python program uses the heapq module to implement a simple priority queue: import heapq
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |