python优先队列实现 [英] python Priority Queue implementation

查看:65
本文介绍了python优先队列实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用以下参数创建插入函数.插入函数应该接收一个优先级队列和一个元素并使用优先级规则插入它 -

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 -

优先级队列会接受一系列任务并对其进行排序基于它们的重要性.每个任务都有一个整数优先级,从 10(最高优先级)到 1(最低优先级).如果两个任务具有相同的优先级,则顺序应以顺序为准它们被插入到优先级队列中(较早的第一个).

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

我正在尝试编写的代码是 insert(element, queue): 它应该使用优先级队列插入元素.同样,myPriorty 是一个从 1 到 10 的整数.

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.

同样,我可以执行以下操作以确保我创建的优先级为 1 到 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)]

这样我就可以用 bval.pq 替换插入任务中的 myPriority

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

推荐答案

双端队列 (from collections import deque) 是单个队列的 Python 实现.您可以在一端添加项目并从另一端删除它们.如果你有每个优先级的双端队列,你可以添加到你想要的优先级.

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

这篇关于python优先队列实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆