这是我在python中实现的MinHeap和MaxHeap。这使用比较器来反转MaxHeap中的存储顺序
import heapq
class MinHeap:
def __init__(self):
self.heap = []
def push(self, item):
heapq.heappush(self.heap, item)
def pop(self):
return heapq.heappop(self.heap)
def peek(self):
return self.heap[0]
def __getitem__(self, item):
return self.heap[item]
def __len__(self):
return len(self.heap)
class MaxHeap(MinHeap):
def push(self, item):
heapq.heappush(self.heap, Comparator(item))
def pop(self):
return heapq.heappop(self.heap)
def peek(self):
return self.heap[0]
def __getitem__(self, i):
return self.heap[i].val
class Comparator:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > other
def __eq__(self, other):
return self.val == other
if __name__ == '__main__':
max_heap = MaxHeap()
max_heap.push(12)
max_heap.push(3)
max_heap.push(17)
print(max_heap.pop())
MinHeap似乎工作正常,但是MaxHeap抛出以下错误。
<__main__.Comparator object at 0x10a5c1080>
我似乎不太了解我在这里做错了什么。有人可以帮我弄这个吗。
最佳答案
我已将__repr__
和__gt__
方法添加到您的Comparator
类中,因此代码现在可以运行,并且Comparator
实例在打印时显示其val
。
重要的是要使这些比较方法在两个Comparator
实例之间正确进行比较。
您会注意到,我从MaxHeap
中删除了大多数方法。不需要它们是因为从MinHeap
继承的方法可以正常工作。您不妨将其还原到MaxHeap
def __getitem__(self, i):
return self.heap[i].val
取决于您打算如何使用
MaxHeap
。import heapq
class MinHeap:
def __init__(self):
self.heap = []
def push(self, item):
heapq.heappush(self.heap, item)
def pop(self):
return heapq.heappop(self.heap)
def peek(self):
return self.heap[0]
def __getitem__(self, item):
return self.heap[item]
def __len__(self):
return len(self.heap)
class MaxHeap(MinHeap):
def push(self, item):
heapq.heappush(self.heap, Comparator(item))
class Comparator:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > other.val
def __eq__(self, other):
return self.val == other.val
def __repr__(self):
return repr(self.val)
if __name__ == '__main__':
max_heap = MaxHeap()
max_heap.push(12)
max_heap.push(3)
max_heap.push(17)
while True:
try:
print(max_heap.pop())
except IndexError:
# The heap's empty, bail out
break
输出
17
12
3
为
Comparator
提供全套丰富的比较方法可能是一个好主意。他们不需要使上面的代码正常工作,但是可以使Comparator
实例更加灵活。因此,如果您需要它们,这里是:def __lt__(self, other):
return self.val > other.val
def __le__(self, other):
return self.val >= other.val
def __gt__(self, other):
return self.val < other.val
def __ge__(self, other):
return self.val <= other.val
def __eq__(self, other):
return self.val == other.val
def __ne__(self, other):
return self.val != other.val