版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_27643275/article/details/88878612
heapq +__lt__
自定义对象结构,并重载__lt__
操作符
import heapq
class MyObject:
def __init__(self, val):
self.val = val
def __lt__(self, other):
return self.val > other.val
q = []
heapq.heappush(q, MyObject(50))
heapq.heappush(q, MyObject(40))
heapq.heappush(q, MyObject(30))
heapq.heappush(q, MyObject(20))
heapq.heappush(q, MyObject(200))
obj = heapq.heappop(q)
print(obj.val)
heapq+lambda
https://stackoverflow.com/questions/8875706/heapq-with-custom-compare-predicate
heapq模块可以接受元组对象,默认按照元组的第一个
元素构成小根堆
heappush( Q , tuple )
如果想要按照元组中的其他元素
构成小根堆,可以通过以下方式进行,在原来基础上加个优先级
即可:
heappush( Q , ( priority, tuple ) )
优先级取负则构成一个大根堆
priority = key(tuple[i])
key=lambda x:x
import heapq
from heapq import *
def FindMaxProfit(costs, profits, key=lambda x: x):
maxHeap = []
for i in range(len(costs)):
heappush(maxHeap, (-key(profits[i]), costs[i], profits[i]))
return heappop(maxHeap)[2]
# for test
costs = [5, 10, 60, 20]
profits = [3, 2, 4, 9]
print(FindMaxProfit(costs, profits)) # 9