The Self-Taught Computer Scientist


Download 1.48 Mb.
Pdf ko'rish
bet127/147
Sana17.06.2023
Hajmi1.48 Mb.
#1540634
1   ...   123   124   125   126   127   128   129   130   ...   147
Bog'liq
books-library.net-11301817Az7X6

C E D H R T L
Figure 15.12: An array with keys at indexes based on their position in the tree.
[0]
[2]
C
E
D
H R T L
Figure 15.13: The right child of the root is at index 2.


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))



Download 1.48 Mb.

Do'stlaringiz bilan baham:
1   ...   123   124   125   126   127   128   129   130   ...   147




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling