1

Everyone says if you push tuple into heapq, it will take the first argument as the comparison factor.

But it's not! I'm curious what's wrong in my code?

for task_name, counter in tasks_counter.items():
    heappush(tasks_q, (-int(counter), task_name, counter))
heapify(tasks_q)
while tasks_q:
    print(tasks_q.pop())

output

(-1, 'G', 1)
(-1, 'F', 1)
(-1, 'E', 1)
(-1, 'D', 1)
(-1, 'C', 1)
(-1, 'B', 1)
(-6, 'A', 6)

I think I should get the item with value A first, right? But it's not.

Any alternative solution to use built-in priority queue with Python?

Another example's output.

enter image description here

newBike
  • 14,385
  • 29
  • 109
  • 192

1 Answers1

6

You are using the pop function of list. You need to use heapq.heappop function instead. It will adjust the list to maintain the heap invariant along the way. See the Basic Examples.

It's also not necessary to call heapify if you start with [] and call heappush repeatedly. heappush already ensures that the heap invariant is maintained.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92