Data Structures
168
print(a_list)
>> ['C', 'E', 'D', 'H', 'R', 'T', 'L']
First, you import the
heapify
function from the
heapq
library.
Then you pass a list to the
heapify
function. As you can see, when you print your heapified list, it is now a
min heap you are storing in
a Python list.
You can use the
heapq
library’s function
heappop
to extract a key from a heap and rebalance it.
Here’s how to remove the root key from a heap and balance its remaining keys:
from
heapq import heapify, heappop
a_list = ['R', 'C', 'T', 'H', 'E', 'D', 'L']
heap = heapify(a_list)
print(a_list)
heappop(a_list)
print("After popping")
print(a_list)
>> ['C', 'E', 'D', 'H', 'R', 'T', 'L']
>> After popping
>> ['D', 'E', 'L', 'H', 'R', 'T']
First,
you import both
heapify
and
heappop
from the
heapq
module:
from heapq import heapify, heappop
Then, you create a heap
by passing your list to the
heapify
function and print it:
a_list = ['R', 'C', 'T', 'H', 'E', 'D', 'L']
heap = heapify(a_list)
print(a_list)
Next, you use the
heappop
function to pop the minimum element from your heap and print the result:
heappop(a_list)
print("After popping")
print(a_list)
You can use a
while
loop to pop all the elements off a heap. Here is how
to create a heap and pop
all of its keys off:
from heapq import heapify, heappop
a_list = ['D', 'E', 'L', 'H', 'R', 'T']
heapify(a_list)
while len(a_list) > 0:
print(heappop(a_list))