CKTIS / Python
heapq.heapreplace
Retira a raiz anterior e conserva o novo elemento num heap do mesmo tamanho.
Versão: Python 3.14; repository image, production runtime not attested
Sintaxe
heapq.heapreplace(heap, item, /)Retira a raiz anterior e conserva o novo elemento num heap do mesmo tamanho.
É útil quando a fila tem de aceitar o substituto independentemente da prioridade. Com [4, 8], inserir 2 devolve 4 e deixa dois elementos com mínimo 2.
Um heap vazio não tem raiz anterior e gera IndexError.
from heapq import heapreplace
h = [4]
assert heapreplace(h, -1) == 4 and h == [-1]
try:
heapreplace([], 7)
except IndexError:
pass
else:
raise AssertionError
Exemplos
import heapq
heap = [4, 8]
print(heapq.heapreplace(heap, 2))
print(heap[0], len(heap))
Resultado
4 2 2
Um heap vazio não tem raiz anterior e gera IndexError.