python堆

堆:二叉树,父节点比子节点值小

列表转化为堆
import heapq
x=[3,4,5,6,7,8,9,1,2]
heapq.heapify(x)
print(x)

运行结果
[1, 2, 5, 3, 7, 8, 9, 6, 4]

加入一个值###堆的属性不变###
import heapq
x=[3,4,5,6,7,8,9,1,2]
heapq.heapify(x)
print(x)

heapq.heappush(x,5)
print(x)
运行结果
[1, 2, 5, 3, 7, 8, 9, 6, 4]
[1, 2, 5, 3, 5, 8, 9, 6, 4, 7]

pop后仍是一个堆
import heapq
x=[3,4,5,6,7,8,9,1,2]
heapq.heapify(x)
print(x)

heapq.heappush(x,5)
print(x)

heapq.heappop(x)
print(x)

运行结果
[1, 2, 5, 3, 7, 8, 9, 6, 4]
[1, 2, 5, 3, 5, 8, 9, 6, 4, 7]
[2, 3, 5, 4, 5, 8, 9, 6, 7]

pushpop:值放入堆中,弹出最小值,堆大小不变,先放进去,再弹出来**
import heapq
x=[1,2,3,4,5,6,7,8,9]
heapq.heapify(x)
w=heapq.heappushpop(x,15)
print(x)
print(w)

运行结果
[2, 4, 3, 8, 5, 6, 7, 15, 9]
1

replace弹出最小的值,推入新的值,堆的大小不变,先弹再放,替换再排序
import heapq
x=[1,2,3,4,5,6,7,8,9]
heapq.heapify(x)
w=heapq.heapreplace(x,0)
print(x)
print(w)
#先把1弹出,再放入0#
运行结果
[0, 2, 3, 4, 5, 6, 7, 8, 9]
1

merge多个已排序的输入合并为一个已排序的输出,返回已排序值的iterator

import heapq
x=[1,3,5,7,9]
y=[2,4,6,8,10]
z=heapq.merge(x,y)
print(list(z))

输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

**nlargest\nsmallest(n,iterable)**从数据集中返回前n个最大\最小元素组成的列表
import heapq
x=[1,3,5,7,9,2,4,8]
y=heapq.nsmallest(3,x)
z=heapq.nlargest(3,x)
print(y)
print(z)

输出:[1, 2, 3]
[9, 8, 7]

你可能感兴趣的:(python,排序算法,开发语言)