LoginSignup
0
0

More than 3 years have passed since last update.

Python #スタック・キュー

Posted at

学習メモ・備忘録

スタックとキュー

後入れ先出し(LIFO)型のバッファがスタック、先入れ先出し(FIFO)型のバッファが キューである。

stackSample.py
stack = []

for i in range(10):
    stack.append(i)
    if len(stack)>4:
        print(stack.pop())

実行結果

4
5
6
7
8
9

queueSample.py
queue = []

for i in range(10):
    queue.append(i)
    if len(queue)>4:
        print(queue.pop(0))

実行結果

0
1
2
3
4
5

ただし、キューをリストで実装するとpop(0)によって先頭のデータが取り出された後、残りのデータを一つづつずらさなければならないため効率が悪いので、collectionsパッケージのdequeを利用する。

dequeSample.py
from collections import deque

queue = deque([])

for i in range(10):
    queue.append(i)
    if len(queue)>4:
        print(queue.popleft())

実行結果

0
1
2
3
4
5

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0