CKTIS / Python
heapq.heapify
Costruisce in tempo lineare un min-heap da una lista esistente.
Versione: Python 3.14; repository image, production runtime not attested
Sintassi
heapq.heapify(heap, /)Costruisce in tempo lineare un min-heap da una lista esistente.
Ogni genitore è minore o uguale a ciascun figlio presente. Riordina la stessa lista e restituisce None. Gli elementi devono essere confrontabili con <. La radice contiene il minimo e non è imposto un ordine fra nodi fratelli.
Nell’esempio l’indice 0 dà 1 e le estrazioni successive danno 1, 3, 7, 8.
from heapq import heapify, heappop
h = [9, 1, 8, 3, 3]
assert heapify(h) is None
assert [heappop(h) for _ in range(5)] == [1, 3, 3, 8, 9]
assert heapify(h) is None and h == []
h = [4, 2, 2, 8, 1]
heapify(h)
assert all(h[(i-1)//2] <= h[i] for i in range(1, len(h)))
Esempi
import heapq
items = [8, 3, 7, 1]
print(heapq.heapify(items))
print(items[0], [heapq.heappop(items) for _ in range(4)])
Risultato
None 1 [1, 3, 7, 8]
Nell’esempio l’indice 0 dà 1 e le estrazioni successive danno 1, 3, 7, 8.