CKTIS / Python
heapq.heappushpop
Combina inserimento ed estrazione del minimo conservando la dimensione dello heap.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
heapq.heappushpop(heap, item, /)Combina inserimento ed estrazione del minimo conservando la dimensione dello heap.
I valori più grandi restano nello heap, utile per conservare i candidati migliori. Uno heap vuoto restituisce il valore ricevuto e resta vuoto.
Con [4, 8] il 2 torna subito, mentre 6 sostituisce la radice 4 e la chiamata restituisce 4.
from heapq import heappushpop
h = []
assert heappushpop(h, 3) == 3 and h == []
h[:] = [3, 7]
assert heappushpop(h, 2) == 2 and h == [3, 7]
assert heappushpop(h, 5) == 3 and sorted(h) == [5, 7]
Esempi
import heapq
heap = [4, 8]
print(heapq.heappushpop(heap, 2), heap)
print(heapq.heappushpop(heap, 6), sorted(heap))
Risultato
2 [4, 8] 4 [6, 8]
Con [4, 8] il 2 torna subito, mentre 6 sostituisce la radice 4 e la chiamata restituisce 4.