Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python, how should I implement a min heap on a list of tuple?

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.)

like image 891
MegaAndyZ Avatar asked Oct 25 '25 05:10

MegaAndyZ


2 Answers

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)
like image 62
pjs Avatar answered Oct 26 '25 19:10

pjs


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')]
like image 32
Gary Bao 鲍昱彤 Avatar answered Oct 26 '25 17:10

Gary Bao 鲍昱彤



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!