1、使用python 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、要删除现有元素,并在一次操作中用新值替换它们,使用python 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 # ------------------------------------
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试