Python优先级队列检查项目是否存在而没有循环
当它应该打印1时,它打印0,因为一个集合与x的交集和另一个集合与x的交集应该是1 我是不是忽略了一些事情?Python优先级队列检查项目是否存在而没有循环,python,Python,当它应该打印1时,它打印0,因为一个集合与x的交集和另一个集合与x的交集应该是1 我是不是忽略了一些事情? 为什么打印0而不是1?您正在将(优先级,值)的元组推送到堆中,但希望exist方法仅对值起作用,因此您应该从堆中获取一个仅值列表/迭代器,如下所示: import heapq class PriorityQueue: def __init__(self): self.heap = [] def push(self, item, priority):
为什么打印0而不是1?您正在将
(优先级,值)
的元组推送到堆中,但希望exist方法仅对值起作用,因此您应该从堆中获取一个仅值列表/迭代器,如下所示:
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)
def exists(self, item):
return item in (x[1] for x in self.heap)