0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[python] dequeの使い方

Last updated at Posted at 2023-03-25

はじめに

経路問題をとくための方法としてdequeが良く使われている。なのでちょっとまとめてみた。
dequeはスタックのようにも、キューのようにも使うことができる。
pop, pushが頻繁な問題において、listよりも優れた速度を示す、らしいです。

Code

import

from collections import deque

dq = deque()
print(dq)
# deque([])

append() : 右に値を追加

dq.append(5)
dq.append(6)
print(dq)
# deque([5,6])

appendleft():左に値を追加

dq.appendleft(4)
dq.appendleft(3)
print(dq)
# deque([3,4,5,6])

extend():右に値を順番に追加

dq.extend([7, 8, 9])
print(dq)
# deque([3,4,5,6,7,8,9])

extendleft():左に値を順番に追加

dq.extendleft([2, 1, 0])
print(dq)
# deque([0,1,2,3,4,5,6,7,8,9])

remove() : 特定の値を削除

dq.remove(7)
dq.remove(8)
dq.remove(9)
print(dq)
# deque([0,1,2,3,4,5,6])

pop() : 右の値を削除し、その値を返す

popValue = dq.pop()
print(popValue)
# 6
print(dq)
# deque([0,1,2,3,4,5])

popleft() : 左の値を削除し、その値を返す

popValue = dq.popleft()
print(popValue)
# 0
print(dq)
# deque([1,2,3,4,5])

rotate() : deque中の値を回転

print(dq)
# deque([1,2,3,4,5])
dq.rotate(1)
print(dq)
# deque([2,3,4,5,1])
dq.rotate(1)
print(dq)
# deque([3,4,5,1,2])
dq.rotate(-1)
print(dq)
# deque([2,3,4,5,1])
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?