![]() However, the list also does not reflect the order in which the assignments have been added to the queue. When you look at the output produced by the print statement in the last line, you may be disappointed because it doesn’t look like the list is really ordered based on the priority numbers of the assignments. ![]() Heapq.heappush(pQueue, 'Assignment ' + str(priority)) The code starts with an empty list in variable pQueue and then simulates the arrival of 100 assignments with random priority using heappush (…) to add a new assignment to the queue. The reason we defined the highest priority to be given by the number 1 and the lowest priority by the number 9 is that heapq implements a min heap in which heappop (…) always returns the lowest value element according to the < relation in contrast to a max heap in which heappop (…) would always return the highest value element. “Assignment 1” < “Assignment 2” < … < “Assignment 9”. In the following code, we again use strings for representing our assignments and encode the priority in the strings themselves so that their lexicographical order corresponds to their priority, i.e. The heapq module among other things provides a set of functions for adding elements to a list (function heappush (…)) and for removing the first item with highest priority (function heappop (…)). ![]() That means we need to make sure we keep the assignments in the queue ordered based on their priority so that taking the first assignment from the queue will be that with the highest priority. Let’s say that instead of performing the assignments in the order in which they arrive (first-in-first-out), the assignments have a priority value between 1 and 9 with 1 meaning highest and 9 meaning lowest priority. The idea of a priority queue is that items in the collection are always kept ordered based on their < relation so that when we take the first item from the queue it will always be the one with lowest (or highest) value.įor instance, let’s get back to the example we started this section with of managing a queue of assignments or tasks that need to be performed.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |