In VS Code, I have a Python heap variable, which is a list of three-item tuples, defined as
heapq.heappush(heap, (len(candidates[(i, j)]), i, j))
At the beginning of debugging, heap[0] is always the tuple with the shortest len(candidates[i, j]). However, after a few rounds of modifying items (not the top item) in the heap by doing -
heap.remove((length, r, c))
heapq.heappush(heap, (length - 1, r, c))
, heap[0] no longer point to the minimum item. For example, in the debug console, heap[0] may show (3, 4, 5), while there exists another heap item (1, 6, 7). Because 1 < 3, obviously (3, 4, 5) shouldn't be above the other item in the heap.
It does not point to the minimum item anymore, since the data structure you have is no longer a heap, after doing a
remove(). Python technically allows you to dolist.remove(x)for some valuex, but the whole point of a heap is to only let you(heap)popor "remove" the lowest value in the heap.Doing
heap.remove()is logically incorrect, and will no longer maintain the heap invariant (thus it will act only as a list). Useheapq.heappop(heap)to remove elements from a heap instead.If you still want to remove specific element from the data structure, and want to have access to the smallest element, you can check out sorted lists in Python here.