How would I write the following Java PriorityQueue in Python?
PriorityQueue<Integer[]> pq = new PriorityQueue<Integer[]>(11,
new Comparator<Integer[]>() {
public int compare(Integer[] A, Integer[] B) {
return A[0] < B[0] ? -1 : 1;
}
});
I got as far as
from Queue import PriorityQueue
def my_method(self):
pq = # I got stuck here since I need to include "comparator"
I have looked through many examples such as Creating a python priority Queue but they don’t seem to be defining a priorty function or comparator of some sort.
One option is to put
(A.pulp, A)as the values in your priority queue. That way, it will use tuple comparisons to comparepulpvalues first.Another option is to implement
__cmp__(or define__lt__and__eq__and usefunctools.total_ordering) on your class to do the necessary comparisons. This assumes you don’t have some other comparison function in place already.