[Python ์ž๋ฃŒ๊ตฌ์กฐ] Queue (ํ) ๊ตฌํ˜„ํ•˜๊ธฐ

2021. 1. 6. 01:41ใ†๐Ÿ“š Algorithm/๐Ÿ“• Python ๋ฌธ๋ฒ•

๋ฐ˜์‘ํ˜•

Queue(ํ) ?!

ํ๋Š” FIFO (First - In - First - Out) ๋กœ์จ ๋จผ์ € ์‚ฝ์ž…๋œ item ์ˆœ์œผ๋กœ ๊บผ๋‚ด์–ด์ง„๋‹ค๊ณ  ์ดํ•ดํ•˜๋ฉด ์‰ฌ์šธ๊ฑฐ ๊ฐ™์Šต๋‹ˆ๋‹ค.

ํ์˜ ์ข…๋ฅ˜์—๋Š” ์ˆœ์ฐจ์ ์ธ ํ์™€ ์›ํ˜• ํ(์›ํ˜•์œผ๋กœ ์ด๋ฃจ์–ด์ง„ Queue)๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

 

Python์—์„œ Queue ๊ตฌํ˜„ํ•˜๊ธฐ

Python์—์„œ๋Š” collections ๋ชจ๋“ˆ์˜ deque ๋ฅผ ํ†ตํ•ด ํ ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค.

 

Deque (๋ฑ) ๊ฐ์ฒด

deque๋Š” ์Šคํƒ๊ณผ ํ๋ฅผ ํ•ฉ์นœ ์ž๋ฃŒ๊ตฌ์กฐ๋กœ ๊ฐ€์žฅ์ž๋ฆฌ์— ์›์†Œ๋ฅผ ๋„ฃ๊ฑฐ๋‚˜ ๋บ„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

deque([iterable[, maxlen]]) deque์˜ ์ดˆ๊ธฐํ™” ํ•จ์ˆ˜ (๋ฆฌ์ŠคํŠธ, queue์˜ ์ตœ๋Œ€ ๊ธธ์ด๋ฅผ ๋„ฃ์„ ์ˆ˜ ์žˆ๋‹ค)
append(x) ์›์†Œ x๋ฅผ deque ๋งจ ์˜ค๋ฅธ์ชฝ์— ์‚ฝ์ž…
popleft() deque์— ๊ฐ€์žฅ ์™ผ์ชฝ์— ์žˆ๋Š” ์›์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋ฉฐ ๊ทธ๊ฐ’์„ ๋ฆฌํ„ด
clear() ๋ชจ๋“  ์›์†Œ๋ฅผ ์ง€์šด๋‹ค.
len(deque) deque์˜ ์›์†Œ์ˆ˜๋ฅผ ์•Œ์•„๋‚ผ ๋•Œ

 

์Šคํƒ๊ณผ ๋‹ฌ๋ฆฌ ํ๋ฅผ list๋กœ ์ด์šฉํ•˜์ง€ ์•Š๋Š” ์ด์œ ๋Š” !?

์Šคํƒ์—์„œ list.append์™€ list.pop()์„ ์ด์šฉํ–ˆ๋˜ ๊ฒƒ ์ฒ˜๋Ÿผ list.append์™€ list.pop(0)์„ ์ด์šฉํ•˜๋ฉด ๋ฆฌ์ŠคํŠธ๋ฅผ ํ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ pop()์˜ time complexity๋Š” O(1)์ธ ๋ฐ˜๋ฉด์— pop(0)์˜ time complexity๋Š” O(N)์ด๊ธฐ ๋•Œ๋ฌธ์— ์‹œ๊ฐ„์ด ์˜ค๋ž˜ ๊ฑธ๋ฆฝ๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ณ ๋ คํ•ด ๋ฆฌ์ŠคํŠธ๋Š” ํ๋กœ ์‚ฌ์šฉํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

 

 

Deque๋ฅผ ์ด์šฉํ•˜์—ฌ Queue ๊ตฌํ˜„ํ•˜๊ธฐ

deque - Init

deque ([iterable[, maxlen]]) ์„ ์ด์šฉํ•ด ์ดˆ๊ธฐํ™” ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

from collections import deque

# ๋นˆ ํ ๋งŒ๋“ค๊ธฐ
deque1 = deque()

# ์›์†Œ๊ฐ€ ์žˆ๋Š” ํ ๋งŒ๋“ค๊ธฐ
deque2 = deque([1, 2, 3])

# ํ ์ตœ๋Œ€ ๊ธธ์ด ๋ช…์‹œํ•˜๊ธฐ(์›์†Œ ์ˆ˜๊ฐ€ maxlen์— ๋„๋‹ฌํ–ˆ์„ ๋•Œ ์ƒˆ๋กœ์šด ๊ฐ’์„ ๋„ฃ์œผ๋ฉด, ์•ž์„œ ๋„ฃ์€ ๊ฐ’์€ ์‚ฌ๋ผ์ง€๊ณ -pop์ด ์ผ์–ด๋‚จ- ๋’ค์— ์ƒˆ ๊ฐ’์ด ๋“ค์–ด๊ฐ)
deque3 = deque(maxlen=5)

 

deque - append(x)

์›์†Œ x๋ฅผ ๋„ฃ์„ ๋•Œ, append()์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

 

from collections import deque
y_deque = deque()
my_deque.append(3)

print(my_deque) #deque([3]

 

deque - popleft()

ํ์—์„œ ์›์†Œ๋ฅผ ์‚ญ์ œํ•  ๋•Œ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

my_deque = deque([1,2,3])

while my_deque:
  print("{}์„/๋ฅผ popํ–ˆ์Šต๋‹ˆ๋‹ค".format(my_deque.popleft())

""" 
1์„/๋ฅผ popํ–ˆ์Šต๋‹ˆ๋‹ค
2์„/๋ฅผ popํ–ˆ์Šต๋‹ˆ๋‹ค
3์„/๋ฅผ popํ–ˆ์Šต๋‹ˆ๋‹ค
"""

 

deque - clear()

๋ชจ๋“  ์›์†Œ๋ฅผ ์ง€์›๋‹ˆ๋‹ค.

my_deque = deque([1,2,3])

print("์ „:", my_deque)

my_deque.clear()

print("ํ›„:", my_deque)
"""
์ „: deque([1, 2, 3])
ํ›„: deque([])
"""

 

deque - len(deque)

len() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ deque์˜ ์›์†Œ ์ˆ˜๋ฅผ ์•Œ์•„๋‚ผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

my_deque = deque([1,2,3], maxlen=5)

print(len(my_deque)) # 3

 

 

ํ•œ๋ฒˆ์— ์ •๋ฆฌํ•œ Python - Queue ์ž๋ฃŒ๊ตฌ์กฐ

 

๋ฐ˜์‘ํ˜•