Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

heapq.heapify

Construye en tiempo lineal un montículo de mínimos a partir de una lista.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

heapq.heapify(heap, /)

Construye en tiempo lineal un montículo de mínimos a partir de una lista.

Cada padre es menor o igual que cada uno de sus hijos existentes. Reordena esa misma lista y devuelve None. Los elementos deben poder compararse con <. La raíz contiene el mínimo y los hermanos carecen de un orden obligatorio.

En el ejemplo el índice 0 da 1 y las extracciones sucesivas dan 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)))

Ejemplos

import heapq
items = [8, 3, 7, 1]
print(heapq.heapify(items))
print(items[0], [heapq.heappop(items) for _ in range(4)])

Resultado

None
1 [1, 3, 7, 8]

En el ejemplo el índice 0 da 1 y las extracciones sucesivas dan 1, 3, 7, 8.

Fuentes