2
votes

I created a new class o object called Element, which has a lot of value 'degree'

class Element(object):
 def __init__(self, name, i):
  self.name = name
  self.degree = i
  # some other values

 #some other functions

 def __cmp__(self, other):
  return cmp(self.degree, other.degree)

And I want to create a priority queue containing this elements:

que = Queue.PriorityQueue()
que.put(Element('element1', 23))
que.put(Element('element2', 45))
que.put(Element('element3', 11))

while not que.empty():
 next_el = que.get()
 print next_el.name + " " + next_el.degree

And the program will print:

element3 11
element1 23
element2 45

But I want to have:

element2 45
element1 23
element3 11

So I want to make, that the element with bigger value of degree has higher priority and is taken first. And the second question is: if two elements has the same value of degree, in which order they will be taken?

2
Then compare them differently. Your first question wasn't really a question. The second question is: in whichever way you define the comparator. Equals will also have to return true or false. - keyser

2 Answers

1
votes

You can just use this method to compare:

def __cmp__(self, other):
    return -cmp(self.degree, other.degree)

This will make element1 < element2 if element1.degree > element2.degree

1
votes

You can modify the comparison method of your Element class to reverse the order:

def __cmp__(self, other):
  return -cmp(self.degree, other.degree)

Negating the return of cmp reverses the queue, because __cmp__ returns positive, negative or zero depending on the result of the comparison:

cmp(a, b) <  0: a <  b
cmp(a, b) >  0: a >  b
cmp(a, b) == 0: a == b