python PriorityQueue模块 heapq模块

Python heapq模块

heap API

heapq.heappush(heap, item) #把item添加到heap中(heap是一个列表)

heapq.heappop(heap) #把堆顶元素弹出,返回的就是堆顶

heapq.heappushpop(heap, item) #先把item加入到堆中,然后再pop,比heappush()再heappop()要快得多

heapq.heapreplace(heap, item) #先pop,然后再把item加入到堆中,比heappop()再heappush()要快得多

heapq.heapify(x) #将列表x进行堆调整,默认的是小顶堆

heapq.merge(*iterables) #将多个列表合并,并进行堆调整,返回的是合并后的列表的迭代器

heapq.nlargest(n, iterable, key=None) #返回最大的n个元素(Top-K问题)

heapq.nsmallest(n, iterable, key=None) #返回最小的n个元素(Top-K问题)

代码示例

import heapq
import random
 
# Top-K
mylist = list(random.sample(range(100), 10))
k = 3
largest = heapq.nlargest(k, mylist)
smallest = heapq.nsmallest(k, mylist)
print('original list is', mylist)
print('largest-'+str(k), '  is ', largest)
print('smallest-'+str(k), ' is ', smallest)
 
# heapify
print('original list is', mylist)
heapq.heapify(mylist)
print('heapify  list is', mylist)
 
# heappush & heappop
heapq.heappush(mylist, 105)
print('pushed heap is', mylist)
heapq.heappop(mylist)
print('popped heap is', mylist)
 
# heappushpop & heapreplace
heapq.heappushpop(mylist, 130)    # heappush -> heappop
print('heappushpop', mylist)
heapq.heapreplace(mylist, 2)    # heappop -> heappush

输出结果

('original list is', [29, 87, 6, 88, 36, 93, 47, 1, 78, 44])
('largest-3', '  is ', [93, 88, 87])
('smallest-3', ' is ', [1, 6, 29])
('original list is', [29, 87, 6, 88, 36, 93, 47, 1, 78, 44])
('heapify  list is', [1, 29, 6, 78, 36, 93, 47, 88, 87, 44])
('pushed heap is', [1, 29, 6, 78, 36, 93, 47, 88, 87, 44, 105])
('popped heap is', [6, 29, 47, 78, 36, 93, 105, 88, 87, 44])
('heappushpop', [29, 36, 47, 78, 44, 93, 105, 88, 87, 130])
('heapreplace', [2, 36, 47, 78, 44, 93, 105, 88, 87, 130])

PriorityQueue 模块

基本操作

常用put(入队列)与get(出队列),queue(查看队列中的元素)。

put方法要注意方入队列的是一个元组,不要忘记括号,默认情况下队列根据元组的第一个元素进行排序。越小的优先级越低。

get方法是将优先级最低的一个元素出队列

代码示例

que = PriorityQueue()
que.put((10,'good'))
que.put((1,'nice'))
que.put((5,'fine'))
while not que.empty():
	print (que.get())

结果输出

(1, 'nice')
(5, 'fine')
(10, 'good')

结合linklist

之所以总结了一下python排序运用比较灵活的两个模块,是看到了LeetCode的一道题 https://leetcode.com/problems/merge-k-sorted-lists/ ,相对于使用sorted 和 手写快排的方法,的确这两个模块更灵活一些,而且效率也很好,而链表还是表常用或者尝尝考到的一个数据结构,所以拿出来总结一下。

参考文章

  1. 日常编程中的python-优先级队列

  2. Python heapq模块

  3. 如何理解算法时间复杂度的表示法O(n²)、O(n)、O(1)、O(nlogn)等

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值