I'm trying to implement a min heap on a list of tuple. For example:
A=[('a',2),('b',1)]
how can I heapify A based on the second element of these tuple, so that A will be heapified to [('b',1),('a',2)]
? (I must maintain a min heap.)
I'm trying to implement a min heap on a list of tuple. For example:
A=[('a',2),('b',1)]
how can I heapify A based on the second element of these tuple, so that A will be heapified to [('b',1),('a',2)]
? (I must maintain a min heap.)
As per @JimMischel's comment, place your tuples in a tuple with the priority as the first element. Then use heapq
:
import heapq
list = [('a', 2), ('b', 1), ('c', 0), ('d', 1)]
heap_elts = [(item[1], item) for item in list]
heapq.heapify(heap_elts) # you specifically asked about heapify, here it is!
while len(heap_elts) > 0:
print(heapq.heappop(heap_elts)[1]) # element 1 is the original tuple
produces:
('c', 0)
('b', 1)
('d', 1)
('a', 2)
import heapq
A=[('a',2),('b',1), ('d', 0), ('c', 2), ('a', 2)]
h = []
for el in A:
heapq.heappush(h, (el[1], el[0]))
print(h)
result:
[(0, 'd'), (2, 'a'), (1, 'b'), (2, 'c'), (2, 'a')]