Python: update element value in heapq

If I have a heapq that contains some elements like:

import heapq class Element(object): def __init__(self, name, val): self.name = name self.val = val if __name__ == "__main__": heap = [] e1 = Element('A', 1) e2 = Element('B', 65) e3 = Element('C', 53) e4 = Element('D', 67) ... heapq.heappush(heap, e1) heapq.heappush(heap, e2) heapq.heappush(heap, e3) heapq.heappush(heap, e4) ... #IF I want to take elements from the heap and print them I will call: while heap: new_e = heapq.heappop(heap) print new_e.name + ' ' + str(new_e.val) 

Suppose I have 50 items in a heap. And I want to change the value of the e3 element from val = 53 to val = 0. So this is NOT the top element of the heap. I also do not want to remove other elements from the heap. How can I make such an update?

+6
source share
1 answer

It is difficult to run the code because there is no way out. However, I tried several things:

In the heapq module heap[0] always indicates the smallest element. In your case, 1 is the smallest item. Therefore, changing this value from 1 to 5 should theoretically be simple. I tried heapq.heappop(heap) , which should return the smallest value. Thus, as you said in your question: โ€œI want to update the val of the element, I donโ€™t know, in turn, thisโ€, this method automatically gets the smallest value (I assume from your question that you want to replace 1 since this is the smallest value , since it is associated with the name First ). However, when I try to run my code, I got <__main__.Element object at 0x103c15dd0> , so you should try to fix your code so that you can print the output, the same thing happens for print heap[0] , the same type of error . Then, as soon as you no longer get this error, at the end of your code block try:

 s = heapq.heappop(heap) print heapq.heapreplace(5, s) 

Using this approach, I get the following error: TypeError: heap argument must be a list Therefore, if you can understand how to convert s to a list, then this should work. Maybe someone can edit my answer to add this code.

Hope this helps.

SELF-EDIT:

Add this to the end of your code block, [] include it in the list that you want to receive as heapq input.

 s = heapq.heappop(heap) print heapq.heapreplace([5], [s]) 

This returns a value of 5 on the output.

Returning to the output problem, if you indicate that you want the result to look, I can try to help you.

0
source

Source: https://habr.com/ru/post/973844/


All Articles