pythonheappriority-queueheapq

Why heappush is taking 3 pararmeter?


Why heappush is taking 3 parameters arr[i].data, i and arr[i]. Why is it taking i as parameter It usually takes one one parameter It is the code for merging k sorted link list

def mergeKLists(arr,K):
# code here
# return head of merged list
    heap = []
    head = tail = Node(0)
    for i in range(K):
        heapq.heappush(heap,(arr[i].data,i,arr[i]))

    while heap:
        node = heapq.heappop(heap)
        node = node[2]
        tail.next = node
        tail = tail.next
        if node.next:
            i += 1
            heapq.heappush(heap,(node.next.data,i,node.next))
    return head.next

Solution

  • actually when tuple is given as input The comparator function will take the first attribute to compare and if they are same it will go to for next attribute and so on if two values are same it will throw "TypeError: unorderable types: Node() < Node()" error So to avoid that, 2nd parameter i which will be unique in the tuple has been taken