import heapq
heap = [] # creates an empty heap
item = [20, 4, 8, 10, 5, 7, 6, 2, 9]
for i in item:
heapq.heappush(heap, i) # pushes a new item on the heap
print('Heap obtained from heappush() : ', heap)
same_item = [20, 4, 8, 10, 5, 7, 6, 2, 9]
heapq.heapify(same_item) # transforms list into a heap, in-place, in linear time
print('Heap obtained from heapify() : ', same_item)
Run Code Online (Sandbox Code Playgroud)
我的理解是heappush()和heapify()应该给出相同的输出,而输出则相反。
Heap obtained from heappush() …
Run Code Online (Sandbox Code Playgroud)