import math
from io import StringIO
def show_tree(tree, total_width=36, fill=' '):
"""Pretty-print a tree."""
output = StringIO()
last_row = -1
for i, n in enumerate(tree):
if i:
row = int(math.floor(math.log(i + 1, 2)))
else:
row = 0
if row != last_row:
output.write('\n')
columns = 2 ** row
col_width = int(math.floor(total_width / columns))
output.write(str(n).center(col_width, fill))
last_row = row
print(output.getvalue())
print('-' * total_width)
print()
import heapq
h = []
l = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
# heappush, push the value item onto the heap
for i in l:
heapq.heappush(h, i)
show_tree(h)
l = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
heapq.heapify(l) # transform list x into a heap
show_tree(l)
l = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
heapq.heapify(l)
# heappop, pop and return the smallest item from the heap
e = heapq.heappop(l)
show_tree(l)
# heapq.heappushpop, push item on the heap, then pop and return the smallest item from the heap
e = heapq.heappushpop(l, 5)
show_tree(l)
# heapq.heapreplace, pop and return the smallest item from the heap, and also push the new item
e = heapq.heapreplace(l, 6)
show_tree(l)
# heapq.nlargest
l2 = heapq.nlargest(4, l)
print(l2) # [16, 14, 10, 9]
# heapq.nsmallest
l3 = heapq.nsmallest(4, l)
print(l3) # [4, 5, 6, 7]
l = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
heapq.heapify(l)
s = [heapq.heappop(l) for i in range(len(l))]
print(s) # [1, 2, 3, 4, 7, 8, 9, 10, 14, 16]
l = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
heapq.heapify(l)
show_tree(l)
# push element into queue
heapq.heappush(l, 5)
show_tree(l)
# pop element
e = heapq.heappop(l)
show_tree(l)