[Python] List VS Queue

Updated:

[Programmers] ๊ธฐ๋Šฅ๊ฐœ๋ฐœ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ํ๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค.

List ๋กœ ๋งŒ๋“ค๊ณ  pop(0) ์œผ๋กœ ๊ตฌํ˜„์„ ํ–ˆ๋Š”๋ฐ ๋ฌธ๋“ ์˜๋ฌธ์ด ๋“ค์—ˆ๋‹ค.

List ์— append, pop ๊ธฐ๋Šฅ์ด ๋‹ค ์žˆ๋Š”๋ฐ ์™œ collections ๋ชจ๋“ˆ์— deque ๋ชจ๋“ˆ์ด ์žˆ๋Š” ๊ฒƒ ์ผ๊นŒ?

๊ฒ€์ƒ‰์„ ํ•ด๋ณด๋˜ ์ค‘ ๋ฐ˜์„ฑ ๋˜ ๋ฐ˜์„ฑ์„ ํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค..

์ž๋ฃŒ๊ตฌ์กฐ ์‹œ๊ฐ„์— ๋ถ„๋ช…ํžˆ ๋ฐฐ์› ๋‹ค.. ๋น…์˜ค! ์ž‘์—…์„ ํ•˜๋Š”๋ฐ ๊ฑธ๋ฆฌ๋Š” ์‹œ๊ฐ„..

๋‹น์—ฐํžˆ List ๋กœ ๋งŒ๋“ค๊ณ  pop(0) ์„ ํ•œ๋‹ค๋ฉด ๋’ค์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋“ค์˜ ์ธ๋ฑ์Šค๋ฅผ ์•ž์œผ๋กœ ์ „๋ถ€ ๋‹น๊ฒจ์ค˜์•ผ ํ•œ๋‹ค.

๊ฒ‰์œผ๋กœ๋Š” O(1) ๊ฐ™์•„ ๋ณด์ด์ง€๋งŒ ์†์œผ๋กœ๋Š” O(n) ์˜ ์‹œ๊ฐ„์ด ๊ฑธ๋ฆฌ๋Š” ๊ฒƒ ์ด๋‹ค.

๊ทธ๋ž˜์„œ ์‹œ๊ฐ„ ๋น„๊ต๋ฅผ ํ•œ ๋ฒˆ ํ•ด๋ดค๋‹ค.

import time
from collections import deque

''' 
    ๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ ํ•œ ํ์™€ ํ๋ฅผ ์‚ฌ์šฉํ•ด ์‹œ๊ฐ„์„ ๋น„๊ต ํ•œ๋‹ค.
    1. ๋ฆฌ์ŠคํŠธ์— append ๋ฅผ ํ•œ ์‹œ๊ฐ„
    2. ํ์— append ๋ฅผ ํ•œ ์‹œ๊ฐ„
    3. ๋ฆฌ์ŠคํŠธ์— pop(0) ์„ ํ•œ ์‹œ๊ฐ„
    4. ๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘์–ด pop() ์„ ํ•œ ์‹œ๊ฐ„
    5. ํ์— popleft() ๋ฅผ ํ•œ ์‹œ๊ฐ„
'''

size = 1000000

start_time = time.time()
_list = []
for i in range(size):
    _list.append(i)
print('๋ฆฌ์ŠคํŠธ์— append ๋ฅผ ํ•œ ์‹œ๊ฐ„ : {}'.format(time.time() - start_time))

start_time = time.time()
_deque = deque()
for i in range(size):
    _deque.append(i)
print('ํ์— append ๋ฅผ ํ•œ ์‹œ๊ฐ„ : {}'.format(time.time() - start_time))

print('-----------------------------------------------------------------')

start_time = time.time()
for i in range(size):
    _list.pop(0)
print('๋ฆฌ์ŠคํŠธ์— pop(0) ์„ ํ•œ ์‹œ๊ฐ„ : {}'.format(time.time() - start_time))

for i in range(size):
    _list.append(i)

start_time = time.time()
_list_rev = _list[::-1]
for i in range(size):
    _list_rev.pop()
print('๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘์–ด pop() ์„ ํ•œ ์‹œ๊ฐ„ : {}'.format(time.time() - start_time))

start_time = time.time()
for i in range(size):
    _deque.popleft()
print('ํ์— popleft ๋ฅผ ํ•œ ์‹œ๊ฐ„ : {}'.format(time.time() - start_time))

๊ฒฐ๊ณผ๋Š” ์–ด๋–ป๊ฒŒ ๋์„๊นŒ ? ๋ฐฑ๋งŒ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์ธก์ •์„ ํ•ด๋ดค๋‹ค.

append ๋Š” ๊ดœ์ฐฎ์ง€๋งŒ pop์—์„œ ์–ด๋งˆ ๋ฌด์‹œํ•œ ์†๋„ ์ฐจ์ด๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค..

๋ฆฌ์ŠคํŠธ๋ฅผ ๋’ค์ง‘์–ด pop() ํ•˜๋Š” ๊ฒฝ์šฐ๋„ ํ๋ฅผ ์‚ฌ์šฉํ•œ ๊ฒฝ์šฐ์™€ ๊ทธ๋ ‡๊ฒŒ ์‹ฌํ•œ ์ฐจ์ด๋Š” ๋‚˜์ง€ ์•Š๋Š”๋‹ค.

๊ทธ๋ ‡๋‹ค๊ณ  ํ๋ฅผ ์‚ฌ์šฉ ํ•  ๋•Œ๋งˆ๋‹ค ๋ฆฌ์ŠคํŠธ๋กœ ๋’ค์ง‘์–ด์„œ ์‚ฌ์šฉ ํ•  ๊ฒƒ์€ ์•„๋‹ˆ๊ธฐ ๋•Œ๋ฌธ์— ์˜๋ฏธ๋Š” ์—†๋‹ค!

์‹œ๊ธฐ ์ ์ ˆํ•˜๊ฒŒ ํ์™€ ๋ฆฌ์ŠคํŠธ๋ฅผ ์‚ฌ์šฉ ํ•˜๋„๋ก ํ•˜์ž..


Categories:

Updated:

Leave a comment