1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| from heapq import *
from random import shuffle
data = range(10)
shuffle(data)
data
[7, 2, 1, 9, 3, 4, 5, 6, 8, 0]
heap = []
for n in data:
heappush(heap, n)
heap
[0, 1, 2, 6, 3, 4, 5, 9, 8, 7]
# heappush(heap, value), heappop(heap), heapify(heap)
heappush(heap, 0.5)
heap
[0, 0.5, 2, 6, 1, 4, 5, 9, 8, 7, 3]
# heappop(heap)
heappop(heap)
0
heappop(heap)
0.5
heap
[1, 3, 2, 6, 7, 4, 5, 9, 8]
# heapify(heap)
heap = [3, 2, 5, 9, 4, 8, 7, 1, 6]
heapify(heap)
heap
[1, 2, 5, 3, 4, 8, 7, 9, 6]
# heapreplace()
heapreplace(heap, 0.5)
1
heap
[0.5, 2, 5, 3, 4, 8, 7, 9, 6]
heapreplace(heap, 10)
0.5
heap
[2, 3, 5, 6, 4, 8, 7, 9, 10]
|