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])