python创建堆的方法有哪些【python堆创建实例】

484次阅读
没有评论

python创建堆的方法有哪些【python堆创建实例】

python创建堆的方法

创建堆有两种基本方法:heappush() 和 heapify()。

当使用heappush()时,当新元素添加时,堆得顺序被保持了。

如果数据已经在内存中,则使用 heapify() 来更有效地重新排列列表中的元素。

python堆创建实例

import heapq
from heapq_showtree import show_tree
from heapq_heapdata import data
 
heap = []
print('random :', data)
print()
 
for n in data:
    print('add {:>3}:'.format(n))
    heapq.heappush(heap, n)
    show_tree(heap)
    
# output
# random : [19, 9, 4, 10, 11]
#
# add  19:
#
#                  19
# ------------------------------------
#
# add   9:
#
#                  9
#         19
# ------------------------------------
#
# add   4:
#
#                  4
#         19                9
# ------------------------------------
#
# add  10:
#
#                  4
#         10                9
#     19
# ------------------------------------
#
# add  11:
#
#                  4
#         10                9
#     19       11
# ------------------------------------
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-04-29发表,共计855字。
新手QQ群:570568346,欢迎进群讨论 Python51学习