python删除堆中元素的方法

368次阅读
没有评论

python删除堆中元素的方法

1、使用heappop()删除具有最小值的元素。

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)
    
# output
# random    : [19, 9, 4, 10, 11]
# heapified :
#
#                  4
#         9                 19
#     10       11
# ------------------------------------
#
#
# pop      4:
#
#                  9
#         10                19
#     11
# ------------------------------------
#
# pop      9:
#
#                  10
#         11                19
# ------------------------------------

2、要删除现有元素,并在一次操作中用新值替换它们,使用heapreplace()。

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)
    
# output
# start:
#
#                  4
#         9                 19
#     10       11
# ------------------------------------
#
# replace  4 with  0:
#
#                  0
#         9                 19
#     10       11
# ------------------------------------
#
# replace  0 with 13:
#
#                  9
#         10                19
#     13       11
# ------------------------------------

以上就是python删除堆中元素的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python基础教程2022-12-07发表,共计1517字。
新手QQ群:570568346,欢迎进群讨论 Python51学习