How to make heapq evaluate the heap off of a specific attribute?

后端 未结 7 717
野的像风
野的像风 2020-11-30 22:07

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq,

7条回答
  •  春和景丽
    2020-11-30 22:48

    I had the same question but none of the above answers hit the spot although some were close but not elaborated enough. Anyway, I did some research and tried this piece of code and hopefully this should be sufficient for someone next who is looking to get an answer:

    The problem with using a tuple is it only uses the first item which is not very flexible. I wanted something similar to std::priority_queue in c++ like this: std::priority_queue, vector>, comparator> pq; where I could design my own comparator which is more common in real world applications.

    Hopefully the below snippet helps: https://repl.it/@gururajks/EvenAccurateCylinders

    import heapq
    class PQNode:
    
        def __init__(self, key, value):
            self.key = key
            self.value = value
    
        # compares the second value
        def __lt__(self, other):
            return self.value < other.value
    
        def __str__(self):
            return str("{} : {}".format(self.key, self.value))
    
    input = [PQNode(1, 4), PQNode(7, 4), PQNode(6, 9), PQNode(2, 5)]
    hinput = []
    for item in input:
        heapq.heappush(hinput, item)
    
    while (hinput):
        print (heapq.heappop(hinput))
    

提交回复
热议问题