python3中的heapq模块使用

heapq-堆排序算法

heapq实现了一个适合与Python的列表一起使用的最小堆排序算法。

创建一个堆

heapq_heapdata.py
# This data was generated with the random module.
data = [19, 9, 4, 10, 11]

heapq_showtree.py
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()

heappush

heapq_heappush.py
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heap = []
print('random :', data)
print()

for n in data:
heapq.heappush(heap, n)
show_tree(heap)

python3 heapq_heappush.py

random : [19, 9, 4, 10, 11]

19
------------------------------------

9
19
------------------------------------

4
19                9
------------------------------------

4
10                9
19
------------------------------------

4
10                9
19       11
------------------------------------

heapify

heapq_heapify.py
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

print('random    :', data)
heapq.heapify(data)
print('heapified :')
show_tree(data)

$python3 heapq_heapify.py random : [19, 9, 4, 10, 11] heapified : 4 9 19 10 11 ------------------------------------ 访问堆的内容 使用heappop()弹出并返回堆中的最小项，保持堆不变。如果堆是空的，则引发IndexError。 heapq_heappop.py import heapq from heapq_showtree import show_tree from heapq_heapdata import data print('random :', data) heapq.heapify(data) print('heapified :') show_tree(data) print() for i in range(2): smallest = heapq.heappop(data) print('pop {:>3}:'.format(smallest)) show_tree(data) 在本例中，使用heapify()和heappop()用于对数字列表进行排序。$ python3 heapq_heappop.py

random    : [19, 9, 4, 10, 11]
heapified :

4
9                 19
10       11
------------------------------------

pop      4:

9
10                19
11
------------------------------------

pop      9:

10
11                19
------------------------------------

heapreplace

heapq_heapreplace.py
import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data

heapq.heapify(data)
print('start:')
show_tree(data)

for n in [0, 13]:
smallest = heapq.heapreplace(data, n)
print('replace {:>2} with {:>2}:'.format(smallest, n))
show_tree(data)

$python3 heapq_heapreplace.py start: 4 9 19 10 11 ------------------------------------ replace 4 with 0: 0 9 19 10 11 ------------------------------------ replace 0 with 13: 9 10 19 13 11 ------------------------------------ 堆中的数据极端值 heapq还包含两个函数，用于检查一个迭代器，并找到它所包含的最大或最小值的范围。 heapq_extremes.py import heapq from heapq_heapdata import data print('all :', data) print('3 largest :', heapq.nlargest(3, data)) print('from sort :', list(reversed(sorted(data)[-3:]))) print('3 smallest:', heapq.nsmallest(3, data)) print('from sort :', sorted(data)[:3]) 使用nlargest（）和nsmallest（）仅对n> 1的相对较小的值有效，但在少数情况下仍然可以派上用场。$ python3 heapq_extremes.py

all       : [19, 9, 4, 10, 11]
3 largest : [19, 11, 10]
from sort : [19, 11, 10]
3 smallest: [4, 9, 10]
from sort : [4, 9, 10]

有效地合并排序Sequences

list(sorted(itertools.chain(*data)))

heapq_merge.py
import heapq
import random

random.seed(2016)

data = []
for i in range(4):
new_data = list(random.sample(range(1, 101), 5))
new_data.sort()
data.append(new_data)

for i, d in enumerate(data):
print('{}: {}'.format(i, d))

print('\nMerged:')
for i in heapq.merge(*data):
print(i, end=' ')
print()

\$ python3 heapq_merge.py

0: [33, 58, 71, 88, 95]
1: [10, 11, 17, 38, 91]
2: [13, 18, 39, 61, 63]
3: [20, 27, 31, 42, 45]

Merged:
10 11 13 17 18 20 27 31 33 38 39 42 45 58 61 63 71 88 91 95

class BigHeap:
def init(self):
self.arr = list()
def heap_insert(self, val):
heapq.heappush(self.arr, -val)
def heapify(self):
heapq.heapify(self.arr)
def heap_pop(self):
return -heapq.heappop(self.arr)
def get_top(self):
if not self.arr:
return
return -self.arr[0]
posted @ 2019-05-09 16:44 公众号python学习开发 阅读(...) 评论(...) 编辑 收藏