python实现各基本数据结构(1)——离散和线性

3 minute read

离散

集合(set)

OperationAverage caseWorst Casenotes
x in sO(1)O(n)
Union stO(len(s)+len(t))
Intersection s&tO(min(len(s), len(t))O(len(s) * len(t))replace “min” with “max” if t is not a set
Multiple intersection s1&s2&..&sn(n-1)*O(l) where l is max(len(s1),..,len(sn))
Difference s-tO(len(s))
s.difference_update(t)O(len(t))
Symmetric Difference s^tO(len(s))O(len(s) * len(t))
s.symmetric_difference_update(t)O(len(t))O(len(t) * len(s))

dict

OperationAverage caseWorst Case
CopyO(n)O(n)
Get ItemO(1)O(n)
Set ItemO(1)O(n)
Delete ItemO(1)O(n)
IterationO(n)O(n)

defaultdict(collections.defaultdict)

defaultdict在处理不存在的key时和dict不同:若某key不存在则用调用default_factory并将其值作为该key的value。例如

from collections import defaultdict
defdict = defaultdict(list)
defdict['boo'].append(1)

线性数据结构

队列

栈(list)

OperationAverage CaseAmortized Worst Case
CopyO(n)O(n)
AppendO(1)O(1)
InsertO(n)O(n)
Get ItemO(1)O(1)
Set ItemO(1)O(1)
Delete ItemO(n)O(n)
IterationO(n)O(n)
Get SliceO(k)O(k)
Del SliceO(n)O(n)
Set SliceO(k+n)O(k+n)
ExtendO(k)O(k)
SortO(n log n)O(n log n)
MultiplyO(nk)O(nk)
x in sO(n)
min(s), max(s)O(n)
Get LengthO(1)O(1)

array

相对list它固定了数据类型,可以节约内存。

队列 (Queue,LifoQueue)

Queue为先进先出(fifo) LifoQueue为后进先出(lifo)

q = Queue.LifoQueue()
q.put(1)
q.put(2)
q.put(3)
while not q.empty():
    print q.get(),

q = Queue.Queue()
q.put(1)
q.put(2)
q.put(3)
while not q.empty():
    print q.get(),

output:

3 2 1 1 2 3

双向队列 double-ended(collections.deque)

线程安全,且deque的popleft(), appendleft(item)比list的pop(0)insert(0, v)要快的多。

OperationAverage CaseAmortized Worst Case
CopyO(n)O(n)
appendO(1)O(1)
appendleftO(1)O(1)
popO(1)O(1)
popleftO(1)O(1)
extendO(k)O(k)
extendleftO(k)O(k)
rotateO(k)O(k)
removeO(n)O(n)

priority queue(Queue.PriorityQueue)

优先队列是利用 heepq实现的

from Queue import PriorityQueue

q = PriorityQueue()
q.put(2)
q.put(1)
q.put(3)
while not q.empty():
	print q.get(),

q.put((2,'b'))
q.put((1,'c'))
q.put((3,'a'))
while not q.empty():
    print q.get(),


class A(object):
    def __init__(self, priority, v):
        self.priority = priority
        self.value = v

    def __cmp__(self, other):
        return cmp(self.priority, other.priority)

q.put(A(2, 'B'))
q.put(A(1, 'C'))
q.put(A(3, 'A'))

while not q.empty():
    next_item = q.get()
    print next_item.value,

output:

1 2 3 (1, 'c') (2, 'b') (3, 'a') C B A
comments powered by Disqus