python で queue and stack



stackはlistのままでオーケー。
append()
pop()

queueは注意が必要
リストをキュー (queue) として使うことも可能です。この場合、最初に追加した要素を最初に取り出します (“first-in, first-out”)。しかし、リストでは効率的にこの目的を達成することが出来ません。追加(append)や取り出し(pop)をリストの末尾に対しておこなうと速いのですが、挿入(insert)や取り出し(pop)をリストの先頭に対しておこなうと遅くなってしまいます(他の要素をひとつずつずらす必要があるからです)。
from collections import deque 
queue = deque(["Eric", "John", "Michael"])
queue.append("Terry")           # Terry arrives
queue.append("Graham")          # Graham arrives
queue.popleft()                 # The first to arrive now leaves
'Eric'
queue.popleft()                 # The second to arrive now leaves
'John'
queue                           # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])


タグ:

python algorithm
最終更新:2015年07月26日 06:18