VSCode Python heap[0] is no longer the min after modifying the heap items

46 Views Asked by At

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.

1

There are 1 best solutions below

2
Tanishq Chaudhary On

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 do list.remove(x) for some value x, but the whole point of a heap is to only let you (heap)pop or "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). Use heapq.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.