堆数据结构(heapq)简单应用
## 堆数据结构(heapq)简单应用
# 堆数据结构 heapq
# 常用方法:nlargest(),nsmallest(),heapify(),heappop()
# 如果需要的个数较小,使用nlargest或者nsmallest比较好
# 如果需要的个数已经接近了序列长度,使用sorted()[:N]获取前N个数据比较好
# 如果只需要唯一一个最大或最小值,则直接使用max()或者min() import heapq nums = [1,3,5,67,7,34,6,8,5,-12,-45,-234,232]
print(heapq.nlargest(3, nums))
# [232, 67, 34]
print(heapq.nsmallest(3, nums))
# [-234, -45, -12] words = ['happy', 'sad', 'fun', 'sweet', 'blue']
print(heapq.nlargest(3, words))
# ['sweet', 'sad', 'happy']
print(heapq.nsmallest(3, words))
# ['blue', 'fun', 'happy'] print(heapq.nsmallest(3, 'qazwsxedcvbnm'))
# ['a', 'b', 'c'] t = (1,2,3,4)
print(heapq.nlargest(2, t))
#[4, 3] students = [
{"name": "Stanley", "score": 94},
{"name": "Lily", "score": 98},
{"name": "Bob", "score": 87},
{"name": "Well", "score": 85}
] print(heapq.nlargest(len(students), students, key=lambda s: s["score"])) # 需要个数为序列长度,不好
"""
[{'name': 'Lily', 'score': 98},
{'name': 'Stanley', 'score': 94},
{'name': 'Bob', 'score': 87},
{'name': 'Well', 'score': 85}]
""" print(sorted(students, key=lambda s: s['score'], reverse=True)) # 好
"""
[{'name': 'Lily', 'score': 98},
{'name': 'Stanley', 'score': 94},
{'name': 'Bob', 'score': 87},
{'name': 'Well', 'score': 85}]
""" nums = [1,3,5,67,7,34,6,8,5,-12,-45,-234,232]
heapq.heapify(nums)
print(nums)
# [-234, -45, 1, 5, -12, 5, 6, 8, 67, 3, 7, 34, 232]
print(heapq.heappop(nums)) # heappop 返回的是序列中的第一个元素,也就是最小的一个元素
# -234 # 使用heapq编写优先级队列
import heapq class PriorityQueue(object):
def __init__(self):
self._queue = []
self._index = 0 def push(self, item, priority):
heapq.heappush(self._queue, (-priority, self._index, item))
# 第一个参数是添加进的目标序列,
# 第二个参数是将一个元组作为整体添加进序列,目的是为了方便比较,
# 在priority相等的情况下,比较_index
# priority为负数使得添加时按照优先级从大到小排序,因为堆排序的序列的第一个元素永远是最小的
self._index += 1 def pop(self):
# 返回按照-priority 和 _index 排序后的第一个元素(是一个元组)的最后一个元素(item)
return heapq.heappop(self._queue)[-1] q = PriorityQueue()
q.push("bar", 2)
q.push("foo", 1)
q.push("gork", 3)
q.push("new", 1) print(q.pop())
print(q.pop())
print(q.pop())
print(q.pop())
"""
gork # 优先级最高
bar # 优先级第二
foo # 优先级与new相同,比较index,因为先加入,index比new小,所以排在前面
new
"""
参考资料:
Python Cookbook, 3rd edition, by David Beazley and Brian K. Jones (O’Reilly).
堆数据结构(heapq)简单应用的更多相关文章
- Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET
Python -- 堆数据结构 heapq - I love this game! - 博客频道 - CSDN.NET Python -- 堆数据结构 heapq 分类: Python 2012-09 ...
- 优先队列(堆) -数据结构(C语言实现)
数据结构与算法分析 优先队列 模型 Insert(插入) == Enqueue(入队) DeleteMin(删除最小者) == Dequeue(出队) 基本实现 简单链表:在表头插入,并遍历该链表以删 ...
- Python实现堆数据结构
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/18 19:47 # @Author : baoshan # @Site ...
- 从一个集合中查找最大最小的N个元素——Python heapq 堆数据结构
Top N问题在搜索引擎.推荐系统领域应用很广, 如果用我们较为常见的语言,如C.C++.Java等,代码量至少也得五行,但是用Python的话,只用一个函数就能搞定,只需引入heapq(堆队列)这个 ...
- python 中的堆 (heapq 模块)应用:Merge K Sorted Lists
堆是计算机科学中一类特殊的数据结构的统称.堆通常是一个可以被看做一棵树的数组对象.在队列中,调度程序反复提取队列中第一个作业并运行,因为实际情况中某些时间较短的任务将等待很长时间才能结束,或者某些不短 ...
- [转载]C++ 堆与栈简单的介绍
在C和C++中,有三种使用存储区的基本方式: [静态存储区(Static Memory)] 在静态存储区中,连接器(linker)根据程序的需求为对象分配空间.全局变量.静态类成员以及函数中的静态 ...
- Redis数据结构之简单动态字符串SDS
Redis的底层数据结构非常多,其中包括SDS.ZipList.SkipList.LinkedList.HashTable.Intset等.如果你对Redis的理解还只停留在get.set的水平的话, ...
- 单链表数据结构 - java简单实现
链表中最简单的一种是单向链表,每个元素包含两个域,值域和指针域,我们把这样的元素称之为节点.每个节点的指针域内有一个指针,指向下一个节点,而最后一个节点则指向一个空值.如图就是一个单向链表 一个单向链 ...
- OI数据结构&&分治 简单学习笔记
持续更新!!! [例题]简单题(K-D tree) 题目链接 线段树 [例题](环上最大连续和) 给定一个长度为n的环形序列A,其中A1与A_n是相临的,现在有q次修改操作,每次操作会更改其中一个数, ...
随机推荐
- .NET开源工作流RoadFlow-表单设计-隐藏域
隐藏域即<input type="hidden" value=""/>标签:
- html跨域获取数据
a.com下的a.html,需要嵌入b.com下的b.html.这时建一个静态页面c.html将c.html放到a.com服务器中.b.html在嵌入c.html.这样,将参数值传输到c.html中, ...
- OpenSUSE 内核编译教程 (kernel 2.6.x)
http://cn.opensuse.org/OpenSUSE_%E5%86%85%E6%A0%B8%E7%BC%96%E8%AF%91%E6%95%99%E7%A8%8B_(kernel_2.6.x ...
- ubuntu 18 下配置 WebStorm 编译 sass
ubuntu 18 下配置 WebStorm 编译 scss 标签(空格分隔): IDE 安装Ruby: sudo apt-get install ruby ruby -v ruby 2.5.1p57 ...
- 路由 vue-router
vue-router官方文档 1.router跳转页面 编程式的导航 this.$router.push('/index'); 2.mode Router构造配置 const router = new ...
- 限定filesize的数据泵导入导出操作案例
使用如下方法导入导出expdp sh/sh dumpfile=ycr_%U.dump directory=exp filesize=2mimpdp sh/sh dumpfile=ycr_%U.dump ...
- 从零开始Vue项目实战(三)-项目结构
目录结构 ├── README.md 项目介绍 ├── index.html 入口页面 ├── build 构建脚本目录 │ ├── build-server.js 运行本地构建服务器,可以访问构建后 ...
- luogu P2424 约数和
嘟嘟嘟 求出[L, R]中每一个数的约数再相加必定会超时,所以换一种思路:枚举约数d. 对于一个约数d,能整除他的数可以写成k * d, (1 <= k <= ⌊n / d⌋),因此约数d ...
- idea + maven + webapp 项目搭建
1.File-> New -> Project
- ubuntu 网桥配置
vim /etc/network/interfaces auto lo iface lo inet loopback auto eth0 auto eth2 auto eth3 iface eth0 ...