Search code examples
pythonpriority-queue

Priority Queue with two Priorities Python


I'm searching for a kind of priority queue which allows me to give two priorites. I want that it just check for the first value then for the second one Here is some Code

import Queue

class Job(object):
    def __init__(self, fpriority, spriority, description, iata , hops, cost):
        self.fpriority = fpriority
        self.spriority = spriority

q = Queue.PriorityQueue()

q.put(Job(2, 5, 'Mid-level job'))
q.put(Job(2, 20, 'Low-level job'))
q.put(Job(1, 20, 'Important job'))

now i want the following order of the elements

Important job
Mid_level job
Low_level job

how can i create such an order with one queue?


Solution

  • class Job(object):
        def __init__(self, fpriority, spriority, description, iata , hops, cost):
            self.fpriority = fpriority
            self.spriority = spriority
    
        def __cmp__(self, other):
            '''Comparisons for Python 2.x - it's done differently in 3.x'''
            if self.fpriority > other.fpriority:
                return 1
            elif self.fpriority < other.fpriority:
                return -1
            else:
                if self.spriority > other.spriority:
                    return 1
                elif self.spriority < other.spriority:
                    return -1
                else:
                    return 0