python: 堆操作 (heapq库)

来源:互联网 发布:淘宝steam慈善包划算吗 编辑:程序博客网 时间:2024/06/07 06:15

API

Op API Annotations Returns heappush heapq.heappush(heap, item) 将单元素压入 小顶堆 有 heappop heapq.heappop(heap) 弹出 堆顶元素 有 heapify heapq.heapify(x) 将list转换为 堆存储 的list

Test

# coding=utf-8origin_list = [1, 3, 5, 2, 4, 6, 0]sorted_list = [0, 1, 2, 3, 4, 5, 6]import heapq # 注意是 小顶堆 噢~# heapify接口 等于循环把list中的元素 push入 堆import copyh = copy.copy(origin_list)heapq.heapify(h)assert h == [0, 2, 1, 3, 4, 6, 5] != origin_list# 也可以自己 手动 一个一个元素 push进 堆h = []for item in origin_list:    heapq.heappush(h, item)# 堆 本身依然是 listassert type(h) == list# 每 pop 一次,该小顶堆就会重新 堆排序 一次assert h == [0, 2, 1, 3, 4, 6, 5] != origin_list != sorted_listh = [heapq.heappop(h) for _ in xrange(len(h))]assert h == sorted_list