Python笔记(10)----集合、堆、双端队列
来源:互联网 发布:mac怎么查找文件夹 编辑:程序博客网 时间:2024/05/18 00:26
集合、堆、双端队列
1、集合
集合set
print set(range(10))print set([0, 1, 2, 3,0,1,2,3, 4, 5])print set(['wo','ni','ta'])
结果:
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
set([0, 1, 2, 3, 4, 5])
set(['wo', 'ni', 'ta'])
a=set([1,2,3])b=set([2,3,4])print a.union(b)c = a & bprint c.issubset(a)print c <= aprint c.issuperset(a)print c >= aprint a.intersection(b)print a & bprint a.difference(b)print a-bprint a.symmetric_difference(b)print a ^ bprint a.copy()print a.copy() is aa = set ()b = set ()print a.add(b)
结果:
set([1, 2, 3, 4])
True
True
False
False
set([2, 3])
set([2, 3])
set([1])
set([1])
set([1, 4])
set([1, 4])
set([1, 2, 3])
False
2、堆
堆heap
1 heappush(heap,X) :将X入堆。
from heapq import *from random import shuffledata = range(10)shuffle(data)heap = []for n in data:heappush(heap,n)print heapheappush(heap,0.5)print heap
结果:
[0, 1, 2, 3, 6, 8, 7, 5, 4, 9]
[0, 0.5, 2, 3, 1, 8, 7, 5, 4, 9, 6]
2 heappop(heap):将堆中最小元素弹出。
print heappop(heap)print heappop(heap)print heappop(heap)print heap
结果:
0
0.5
1
[2, 3, 7, 4, 6, 8, 9, 5]
3 heapify(heap):将heap属性强制应用到任意一个列表。
heapreplace(heap,X):将heap中最小的元素弹出,并将X入堆。
heap = [3,2,1,4,5,7,6]heapify(heap)print heapheapreplace(heap,0.5)print heapheapreplace(heap,10)print heap
结果:
[1, 2, 3, 4, 5, 7, 6]
[0.5, 2, 3, 4, 5, 7, 6]
[2, 4, 3, 10, 5, 7, 6]
3双端队列
双端队列deque
from collections import dequeq = deque(range(5))q.append(5)q.appendleft(6)print qprint q.pop()print q.popleft()q.rotate(3)print qq.rotate(-1)print q
结果:
deque([6, 0, 1, 2, 3, 4, 5])
5
6
deque([2, 3, 4, 0, 1])
deque([3, 4, 0, 1, 2])
阅读全文
0 0
- Python笔记(10)----集合、堆、双端队列
- python中三种特殊数据结构:set集合、堆、双端队列
- python基础教程_学习笔记19:标准库:一些最爱——集合、堆和双端队列
- python入门系列13―——集合、双端队列、堆
- 优先队列(堆)优先级设置笔记
- 优先队列(堆)笔记 c++
- Java 集合深入理解(10):Deque 双端队列
- Java 集合深入理解(10):Deque 双端队列
- Java 集合深入理解(10):Deque 双端队列
- 优先队列(堆)--二叉堆学习笔记
- 排序算法集合(1)-Python实现的堆排序
- 算法笔记2-优先队列(堆)(上)
- 数据结构笔记(5)优先队列(堆)
- 数据结构学习笔记(六)堆-优先队列
- 数据结构学习笔记(六)优先级队列、堆和左高树
- python 双端队列
- 优先队列(堆)
- 优先队列(堆)
- redis主从复制
- TortoiseSVN设置独占锁
- json 格式化输出
- js数值四舍五入
- LintCode 405-和为零的子矩阵
- Python笔记(10)----集合、堆、双端队列
- android.content.res.Resources$NotFoundException: Resource ID XXX问题解决
- javaWeb服务详解(含源代码,测试通过,注释) ——web.xml
- HDU 2818 Building Block (带权并查集)
- Android Spanned实现TextView富文本效果(1)--文字
- 数据压缩实验五:JPEG文件解码实验分析
- redis的哨兵Sentinel
- SQL查询字符串和数字的一个问题
- yii2验证码