适用于Python的ADT优先级队列

时间:2019-03-19 06:01:38

标签: python

我无法修复该错误。 python的新手。我需要在Python代码中使用优先级队列。寻找高效的东西 我正在尝试生成10个随机数,并将其应用于下面提供的优先级队列。我运行了代码并得到了:TypeError:无法散列的类型:'list'

import heapq
import itertools
import random

class PQ_Heap(object):

    def __init__(self):
        print ("creates a min heap from passed in list")
        self.heap = []
        self.entries = {}
        self.counter = itertools.count()

    def enQueue(self, item, priority):
        print ("adds an item to the PQ and reheapifies")
        if item in self.entries:
            self.remove(item)

        count = next(self.counter)
        # weight = -priority since heap is a min-heap
        entry = [-priority, count, item]
        self.entries[item] = entry
        heapq.heappush(self.heap, entry)
        pass

    #Add an item to the PQ and reheapify. Print out parent and children (if applicable) or n/a if not          
    def deQueue(self):
        print("removes the highest priority item from the PQ and    reheapifies")
        while self.heap:
            weight, count, item = heapq.heappop(self.heap)
            if item is not PriorityQueue._REMOVED:
                del self.entries[item]
                return -weight, item
        raise KeyError("The priority queue is empty")

    #Remove the highest priority item from the PQ and reheapify
    def sneakAPeek(self):
        print ("returns the highest priority in the PQ, but does not remove it") 
        while self.heap:
            weight, count, item = self.heap[0]
            if item is PriorityQueue._REMOVED:
                heapq.heappop(self.heap)
            else:
                return -weight, item

        return None

#       Return the highest priority item from the PQ, but don't remove it 

    def isEmpty(self):
        print ("returns T if PQ is empty, F if PQ has entries")
        if len (self.heap) == 0:
            return 'T'
        return 'F'
#       Return a T if PQ is empty, F if PQ is not empty 
#
    def size(self):
        print ("returns number of items in queue")
        return len (self.heap)


#       Return the number of items in the queue 

q = PQ_Heap()
item1 = [random.randrange(50000) for _ in range(10)]
q.enQueue(item1, 1)

1 个答案:

答案 0 :(得分:1)

这是因为您的队列中需要可散列的实体,但是您将整个列表作为参数传递,而您应将列表中的项目作为参数传递。见下文

    q = PQ_Heap()
    item1 = [random.randrange(50000) for _ in range(10)]
    for item in item1:
        q.enQueue(item, 1)