-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathheap.py
More file actions
93 lines (72 loc) · 1.67 KB
/
heap.py
File metadata and controls
93 lines (72 loc) · 1.67 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -*- coding: utf-8 -*-
"""
堆排序问题
"""
import heapq
# heapq默认是小顶堆
# TODO:可用于实现priorityQueue类的功能
nums = [1, 3, 2, 5, 4]
# 构建小顶堆
pq = []
for num in nums:
heapq.heappush(pq, num)
res = []
while pq:
res.append(heapq.heappop(pq))
print(res)
# 默认是用iterator的索引0作为比较标准
nums = [(1, 'jack'), (3, 'tom'), (2, 'jerry')]
pq = []
for num in nums:
heapq.heappush(pq, num)
res = []
while pq:
res.append(heapq.heappop(pq))
print(res)
nums = [1, 3, 2, 5, 4]
# 构建大顶堆
pq = []
for num in nums:
heapq.heappush(pq, -num)
res = []
while pq:
res.append(-heapq.heappop(pq))
print(res)
# 自定义排序标准
class State(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __lt__(self, other): # 小于则是小顶堆,大于则是大顶堆
return self.y < other.y
a = State(3, 1)
b = State(2, 3)
c = State(2, 2)
pq = []
for n in [a, b, c]:
heapq.heappush(pq, n)
res = []
while pq:
cur_state = heapq.heappop(pq)
res.append((cur_state.x, cur_state.y))
print(res)
# json对象的小顶堆
class State(object):
def __init__(self, x, field):
self.x = x
self.field = field
def __lt__(self, other):
if self.field not in self.x or other.field not in other.x:
return False
return self.x[self.field] < other.x[other.field]
a = State(x={'age': 18, 'name': 'zs'}, field='age')
b = State({'age': 20, 'name': 'ls'}, 'age')
c = State({'age': 19, 'name': 'ww'}, 'age')
pq = []
for n in [a, b, c]:
heapq.heappush(pq, n)
res = []
while pq:
cur_state = heapq.heappop(pq)
res.append(cur_state.x)
print(res)