I am new to Python so excuse for the silly mistakes... I am trying to create a priority queue using heap in python(2.7.15) and my code doesn't obviously work.
pq = [] # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
count = 0 # unique sequence count
def push(pq,task,priority=0):
'Add a new task'
count = count+1
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def update(pq,task, priority=0):
'Add a new task or update the priority of an existing task'
if task in entry_finder:
remove_task(task)
count = count+1
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry)
def remove_task(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_finder.pop(task)
entry[-1] = REMOVED
def pop(pq):
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')
def IsEmpty(pq):
if not pq:
print("List is empty")
Thats what I have done,most of them are taken by here: https://docs.python.org/2/library/heapq.html. My problem is when I try to run it on the python interprenter,I get this:
>>> pq=[]
>>> pq.push("task1",1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'push'
My question is what can I do to avoid this error and if my code has any flaws that maybe can cause further errors?
listand tries to access a method that it doesn't have.if __name__ == '__main__':and then call your methods.