If you don't want an O(n) routine you need to use internal _siftup
and _siftdown
(yes you need to use both because after the swap the element may need swim down as it may need to float up). You decide if that's deterrent for you or not, but here it goes.
import heapq
# The removal function using internal functions
def remove_item(heap, val):
if not heap:
return
try:
i = heap.index(val)
except ValueError:
return
if i < len(heap) - 1:
heap[i] = heap[-1]
heap.pop()
if i < len(heap):
heapq._siftup(heap, i)
heapq._siftdown(heap, 0, i)
# Initial state
a = range(30)
a.reverse()
heapq.heapify(a)
print(a)
# The removal
remove_item(a, 15)
print(a)
Kudos to Duncan: https://stackoverflow.com/a/10163422/292502