Python优先级队列检查以查看项是否存在而没有循环

时间:2013-08-12 07:45:43

标签: python

import heapq
class PriorityQueue:

    def __init__(self):
        self.heap = []

    def push(self, item, priority):
        pair = (priority,item)
        heapq.heappush(self.heap,pair)

    def pop(self):
       return heapq.heappop(self.heap)

    def isEmpty(self):
        return len(self.heap) == 0

    def clear(self):
        while not (self.isEmpty()):
            self.heap.pop()

    def getHeap(self):
        return self.heap

    def getLeng(self):
        return len(self.heap)

    def exists(self, item):
       return len(list(set(self.heap) & set(item)))

pq = PriorityQueue()
x = "test"
pq.push(x,1)
print pq.exists(x)     

当它打印1时打印0,因为一组x与另一组x的交点应为1

我是否忽视了一些事情? 为什么打印0而不是1?

1 个答案:

答案 0 :(得分:3)

您正在将(priority,value)的元组推送到堆中,但希望exists方法仅适用于值,因此您应该从堆中获取一个仅限值的列表/迭代器,如下所示:

def exists(self, item):
   return item in (x[1] for x in self.heap)