I'm trying to incorporate the advice found in https://docs.python.org/3.5/library/heapq.html in order to make a priority queue implementation (see corresponding section) in a class priorityQ
. Not going to reinvent the wheel so i use the the python's heapq implementation
class priorityQ():
import heapq
import itertools
def __init__(self,mylist):
self._entry_finder = {} # mapping of tasks to entries
self._counter = itertools.count() # unique sequence count
self.REMOVED = '<removed-task>' # placeholder for a removed task
if mylist:
self.data = []
for element in mylist:
priority, count, task = element[0], next(self._counter), element[1]
entry = [priority,count,task]
self._entry_finder[task] = entry
heapq.heappush(self.data,entry)
else:
self.data = []
def add_task(self,task,priority):
if task in self._entry_finder:
self.remove_task(task)
count = next(self._counter)
entry = [priority,count,task]
self._entry_finder[task] = entry
heapq.heappush(self.data, entry)
def remove_task(self,task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = self._entry_finder.pop(task)
entry[-1] = self.REMOVED
def pop_task(self):
while self.data:
priority, count, task = heapq.heappop(self.data)
if task is not self.REMOVED:
del self._entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')
The code as it is seems to solve the implementation challenges listed in 8.5.2 in the link I gave. I just wonder if this is a clean implementation of such a candidate class. Is it better to just implement with the procedural style suggested in the manual and incorporate it in whatever project i'm working on or is it a better practice to make use of a class like the above (or a more refined version of that).
PS: I know it's slightly off-topic for this stack exchange site, but i wonder if there is a way around the side effect of having a bunch of deleted-entries residing in the queue after doing a set of priority updates in existing tasks. (Something different than copying/cleaning the entire queue every fixed period of time)