Home > Blockchain >  How python PriorityQueue works with irregular tuple object
How python PriorityQueue works with irregular tuple object

Time:11-19

Error occurs in the following code, and we can't see the source code or debug into it.
I wonder

  1. the real reason PriorityQueue(or heapq) works inner;
  2. how to solve this phenomenon.
import numpy as np
from queue import PriorityQueue

q = PriorityQueue()
q.put((0, np.array([True, True])))
q.put((0, np.array([True, False])))
"""
Traceback (most recent call last):
  File "D:/code-study/py/A/B.py", line 6, in <module>
    q.put((0, np.array([True, False])))
  File "D:\ProgramData\Anaconda3\lib\queue.py", line 149, in put
    self._put(item)
  File "D:\ProgramData\Anaconda3\lib\queue.py", line 233, in _put
    heappush(self.queue, item)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
"""

CodePudding user response:

The problem is that comparing two numpy arrays doesn't return True or False. Priority queues work by literally comparing the two elements using <, and expecting to get back True or False.

It is conventional to put your data in a priority queue as (priority, actual_data), but that is just convention. The actual comparison is between the full elements. When Python compares two tuples and the first item in the tuples are equal, it then compares the second element of each. And that's what's giving you an error.

A standard trick is to keep a counter, and increment it by one each time you add an element to the queue. So your values are (priority, counter, actual_data). Since every element in the queue has a different second value, the actual data will never ben compared. Items that have the same priority will be handled in a FIFO order.

  • Related