集合、堆、双端队列
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 & b
print c.issubset(a)
print c <= a
print c.issuperset(a)
print c >= a
print a.intersection(b)
print a & b
print a.difference(b)
print a-b
print a.symmetric_difference(b)
print a ^ b
print a.copy()
print a.copy() is a
a = 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 shuffle
data = range(10)
shuffle(data)
heap = []
for n in data:
heappush(heap,n)
print heap
heappush(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 heap
heapreplace(heap,0.5)
print heap
heapreplace(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 deque
q = deque(range(5))
q.append(5)
q.appendleft(6)
print q
print q.pop()
print q.popleft()
q.rotate(3)
print q
q.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])