2013-08-12 52 views
1
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)  

它印0時,它應該打印1,因爲一組與x和另一組隨着x的交叉點應是1個Python的優先隊列檢查以查看是否存在項目,而不循環

我俯瞰東西?
爲什麼它打印0而不是1?

回答

3

您正在推動的(priority,value)元組堆,但希望存在方法上的價值只有工作,所以你應該得到一個唯一的價值列表/迭代器,你的堆,這樣的事情:

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