1.首先了解queue模块
主要了解它的三个对象就好。
1.1 FIFO:队列queue.Queue()
print("*"*10, "队列", "*"*10)
q_queue = queue.Queue()
for i in range(5):
q_queue.put(i)
while not q_queue.empty():
print(q_queue.get())
output : 0 1 2 3 4
1.2 FILO:栈queue.LifoQueue()
print("*"*10, "栈", "*"*10)
q_stack = queue.LifoQueue()
for i in range(5):
q_stack.put(i)
while not q_stack.empty():
print(q_stack.get())
output : 4 3 2 1 0
1.3 优先队列: queue.PriorityQueue()
print("*"*10, "优先队列", "*"*10)
# PriorityQueue(priority_number, data)
# 优先等级值越小,优先级越高.
q_proir = queue.PriorityQueue()
q_proir.put((5 * -1, 'Python'))
q_proir.put((4 * -1, 'C'))
q_proir.put((3 * -1, 'Js'))
print("Inside PriorityQueue: ", q_proir.queue) # 内部存储
while not q_proir.empty():
print(q_proir.get()[1])
output : Python C Js
2.了解heapq模块
这是一个最小堆。主要包含三个方法。
- heapify(iterable):使用iterable对象构造堆
- heappush(heap, ele):向堆中插入数据
- heappop(heap):从堆中移除并获得最小的元素
1.1 heappush 依次往堆里添加数据
print("*"*10, "heappush", "*"*10)
# 依次往堆内加入数据
for n in data:
print('add {}'.format(n))
heapq.heappush(heap, n)
show_tree(heap)
print(heap)
1.2 heapify 同时加入数据
print("*"*10, "heapify", "*"*10)
# 同时加入数据
heapq.heapify(data)
print('heapified :')
print(data)
1.3 heappop 删除最小值数据
print("*"*10, "heappop", "*"*10)
# 删除最小值数据
for i in range(2):
smallest = heapq.heappop(data)
print('pop {}:'.format(smallest))
print(data)
3.完整代码
查看链接:
heapq:https://github.com/Wind0ranger/LeetcodeLearn/blob/master/model/test_heapq.py
queue:https://github.com/Wind0ranger/LeetcodeLearn/blob/master/model/test_queue.py
网友评论