-1

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
  • 1
    It is not taking three parameters, and it does not normally take one parameter. It is taking two parameters, just like it always does. The first parameter is `heap`, the heap that will be pushed onto; and the second parameter is `(arr[i].data,i,arr[i])`, the value that will be pushed onto the heap, which is a tuple. Anyway, Stack Overflow is the wrong place "help me understand someone else's code". You should try a proper learning-Python forum, such as https://reddit.com/r/learnpython. – Karl Knechtel Mar 18 '21 at 10:10

2 Answers2

0

It doesn't. In your code you are pushing a tuple to the heap but this is not a requirement. For instance:

import heapq

h = [1, 2, 3, 4]
heapq.heapify(h)

v = heapq.heappop(h) # Returns 1

heapq.heappush(h, 6) # Now h = [2, 3, 4, 6]
Mathieu
  • 5,410
  • 6
  • 28
  • 55
0

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