Search code examples
pythonpriority-queue

python Priority Queue implementation


i'm having trouble creating an insert function with the following parameters. The insert function should take in a priority queue, and an element and inserts it using the priority rules -

The priority queue will take a series of tasks and order them based on their importance. Each task has an integer priority from 10 (highest priority) to 1 (lowest priority). If two tasks have the same priority, the order should be based on the order they were inserted into the priority queue (earlier first).

So, as of right now i've created the following code to initialize some of the things needed...

class Tasks():
    __slots__ = ('name', 'priority')

     def __init__(bval):
         bval.name = myName
         bval.priority = myPriority
         return bval

class PriorityQueue():
    __slots__ = ('queue', 'element')

     def __init__(aval):
         aval.queue = queue
         aval.element = element
         return aval

The code i'm trying to write is insert(element, queue): which should insert the elements using the priority queue. Similarly, myPriorty is an integer from 1 to 10.

Similarly can I do the following to insure that I create a priority from 1 to 10...

def __init__(bval , myPriority = 10):
      bval.priority = myPriority
      bval.pq = [[] for priority in range(bval.myPriority)]

so that I can replace myPriority in the insert task with bval.pq


Solution

  • A deque (from collections import deque) is the python implementation of a single queue. You can add items to one end and remove them from the other. If you have a deque for each priority level, you can add to the priority level you want.

    Together, it looks a bit like this:

    from collections import deque
    
    class PriorityQueue:
        def __init__(self, priorities=10):
            self.subqueues = [deque() for _ in range(levels)]
    
        def enqueue(self, priorty, value):
            self.subqueues[priority].append(value)
    
        def dequeue(self):
            for queue in self.subqueues:
                try:
                    return queue.popleft()
                except IndexError:
                    continue