1

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.

Community
  • 1
  • 1
learner
  • 11,490
  • 26
  • 97
  • 169
  • if A.pulp == B.pulp, you should return 0 – Mel Nicholson Jan 28 '13 at 23:35
  • Is this another pathetic down-vote? Is this from the guy whose response got down-voted so that he deleted his response. I didn't down-vote your response -- although I should have since it was way off. – learner Jan 28 '13 at 23:39

1 Answers1

1

One option is to put (A.pulp, A) as the values in your priority queue. That way, it will use tuple comparisons to compare pulp values first.

Another option is to implement __cmp__ (or define __lt__ and __eq__ and use functools.total_ordering) on your class to do the necessary comparisons. This assumes you don't have some other comparison function in place already.

nneonneo
  • 171,345
  • 36
  • 312
  • 383