没有内置Python函数的优先级队列

时间:2019-01-15 08:39:01

标签: python-3.x priority-queue

我正在尝试为机械工程项目设置新服务器。我计划在服务器上运行优先级队列,以对其下一步的工作进行排序。大多数机械工程师都不知道如何编码,所以我找不到很多人要帮助。

由于难以理解的原因,我需要避免使用python内置的大多数函数。我想将自己限制在以下范围:弹出,插入,if语句等。我写了一篇简单的文章,但是,我需要一个函数来在输入值时进行计算。当前的代码基本上会在末尾排序。

我想将其放入PriorityQueue类: 然后允许它根据项目输入进行排序

class Queue:
  def __init__(self, iL=[]):
    self.aList = iL[:] 

  def enqueue(self, newItem:'item'):
    """put an item in back the queue"""
    # your code...
    self.aList.append(newItem)

  def dequeue(self)->'item': #return the item
    """remove an item from front of the queue, return the item"""
    # your code...
    return self.aList.pop(0)

  def empty(self):
    """Is the queue empty?"""
    # your code...
    return self.aList == []

  def __repr__(self): # for testing only
    return repr(self.aList)


# Use the Queue class as a Priority Queue by
# having a priority associated with each item, e.g.: 
# (2,'code') where item 'code' have priority 2
# (1, 'eat') this entry has a priority 1 and the item 'eat'
# (3, 'sleep') 'sleep' has priority 3
# Let's consider #1 to be the highest priority, be #1, then 2, then 3

# given this type of priority queue as input
# define a function to sort the queue,
# such that highest priority item (smallest number)will be served first
# return a sorted queue

def queueSorted(qu:Queue) -> Queue:
    # your code...
    # must use only those 3 queue functions
    # cannot use any python function for sorting
    qusorted = Queue()
    while not qu.empty():
      # find min, enqueue it into sorted
      qutemp = Queue()
      imin = qu.dequeue()
      while not qu.empty():
        itemp = qu.dequeue()
        if itemp < imin:
          itemp, imin = imin, itemp
        qutemp.enqueue(itemp)
      qusorted.enqueue(imin)
      # do rest
      qu = qutemp
    return qusorted

0 个答案:

没有答案