Python:在优先级队列实现中使用我的堆

Python:在优先级队列实现中使用我的堆,python,heap,priority-queue,binary-heap,Python,Heap,Priority Queue,Binary Heap,在优先级队列类中使用自定义堆类函数时,我遇到了真正的问题。我在堆类中的哪些函数用于PriorityQueue的“enqueue”、“dequeue”、“front”和“size”函数时遇到了问题。我知道对于“排队”,我需要使用insert函数,但我不知道如何进行,因为我有一个优先级。有人能帮我做些什么,让我的PriorityQueue类使用Heap类中的函数才能正常工作吗?我已经在这个问题上停留了一段时间,我一直在寻找答案,包括使用内置的python函数,如queue和heapq 类堆(对象):

在优先级队列类中使用自定义堆类函数时,我遇到了真正的问题。我在堆类中的哪些函数用于PriorityQueue的“enqueue”、“dequeue”、“front”和“size”函数时遇到了问题。我知道对于“排队”,我需要使用insert函数,但我不知道如何进行,因为我有一个优先级。有人能帮我做些什么,让我的PriorityQueue类使用Heap类中的函数才能正常工作吗?我已经在这个问题上停留了一段时间,我一直在寻找答案,包括使用内置的python函数,如queue和heapq

类堆(对象):

到目前为止,这是我得到的,但我不知道这是否完全正确。有人能帮我吗


我把我的代码编辑成最新版本。

因为这大概是我的家庭作业,所以我所能做的就是给出提示,这通常作为注释更容易完成。因为这是一系列相当彻底的提示,所以我在这里总结它们作为一个答案

在大多数情况下,
PriorityQueue
类中的方法将映射到堆类中已经实现的方法:

  • PriorityQueue.enqueue()
    很容易映射到Heap.insert()
  • PriorityQueue.first()
    没有相应的堆方法,但仍然可以在一行中实现。您只需要返回最大值,它将始终位于堆中的特定位置
  • PriorityQueue.dequeue()
    有点复杂。它需要先保存顶部项的值,以便在调用
    heap.delete_max()
  • heap类已经有了一个
    size()
    方法,该方法可以调用
    PriorityQueue.size()
    而不是在
    PriorityQueue
    类中维护一个单独的大小变量
此外,您需要一个init函数,这将创建一个新的Heap对象,该对象将由类维护


为了生成迭代器,您需要生成一个新类。它需要维护一个整数变量(我们称之为
self.index
),指示它在队列中的当前位置。您还需要一个增加self.index并返回上一个索引位置的值的方法。应该就是这样。

您是否遇到了特定的问题?判断代码是否正确的最佳方法是测试代码。不过,从表面上看,dequeue并不像它所说的那样返回最高优先级的项目,而是将其删除。显然第一个仍然没有实现(提示:这是一个单行程序)。我需要创建一个init函数吗?像这样的
def\uuu init\uuuu(self):self.head=None
然后对于前端执行此操作
def first(self):返回self.head[0]
?您的思路完全正确,但为什么需要self.head?您已经有self.heap,最大值只能在堆中的一个特定位置。。。(一个init函数对于所有类来说都是一件好事——我不完全确定在没有它的情况下如何初始化self.heap)@seaotternerd好的,我想我理解你的意思。我编辑了我的代码。到目前为止,你看这是否适合你?是的,这对于
first()
来说非常完美。您需要添加类似于“出列”的内容,以便可以返回删除的项目。另外,不为PriorityQueue类维护单独的大小变量可能更简单,因为您可以只使用堆的
size()
方法。
    def __init__(self, items=None):

        '''Post: A heap is created with specified items.'''

        self.heap = [None]
        if items is None:
            self.heap_size = 0
        else:
            self.heap += items
            self.heap_size = len(items)
            self._build_heap()

    def size(self):

        '''Post: Returns the number of items in the heap.'''

        return self.heap_size

    def _heapify(self, position):

        '''Pre: Items from 0 to position - 1 satisfy the Heap property.
       Post: Heap Property is satisfied for the entire heap.'''

        item = self.heap[position]
        while position * 2 <= self.heap_size:
            child = position * 2
            # If the right child, determine the maximum of two children.
            if (child != self.heap_size and self.heap[child+1] > self.heap[child]):
                child += 1
            if self.heap[child] > item:
                self.heap[position] = self.heap[child]
                position = child
            else:
                break
        self.heap[position] = item

    def delete_max(self):

        '''Pre: Heap property is satisfied
       Post: Maximum element in heap is removed and returned. '''

        if self.heap_size > 0:
            max_item = self.heap[1]
            self.heap[1] = self.heap[self.heap_size]
            self.heap_size -= 1
            self.heap.pop()
            if self.heap_size > 0:
                self._heapify(1)
            return max_item

    def insert(self, item):

        '''Pre: Heap Property is Satisfied.
       Post: Item is inserted in proper location in heap.'''

        self.heap_size += 1
        # extend the length of the list.
        self.heap.append(None)
        position = self.heap_size
        parent = position // 2
        while parent > 0 and self.heap[parent] < item:
            # Move the item down.
            self.heap[position] = self.heap[parent]
            position = parent
            parent = position // 2
        # Puts the new item in the correct spot.
        self.heap[position] = item

    def _build_heap(self):

        ''' Pre: Self.heap has values in 1 to self.heap_size
           Post: Heap property is satisfied for entire heap. '''

        # 1 through self.heap_size.

        for i in range(self.heap_size // 2, 0, -1): # Stops at 1.
            self._heapify(i)

    def heapsort(self):

        '''Pre: Heap Property is satisfied.
           Post: Items are sorted in self.heap[1:self.sorted_size].'''

        sorted_size = self.heap_size

        for i in range(0, sorted_size -1):
            # Since delete_max calls pop to remove an item, we need to append a dummy value to avoid an illegal index.
            self.heap.append(None)
            item = self.delete_max()
            self.heap[sorted_size - i] = item
#PriorityQueue.py
from MyHeap import Heap


class PriorityQueue(object):

    def __init__(self):
        self.heap = None

    def enqueue(self, item, priority):
        '''Post: Item is inserted with specified priority in the PQ.'''
        self.heap.insert((priority, item))

    def first(self):
    '''Post: Returns but does not remove the highest priority item from the PQ.'''
        return self.heap[0]

    def dequeue(self):
    '''Post: Removes and returns the highest priority item from the PQ.'''
    if self.heap is None:
        raise ValueError("This queue is empty.")
    self.heap.delete_max()

    def size(self):
    '''Post: Returns the number of items in the PQ.'''
        return self.size