티스토리 뷰

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성하였습니다.

 

오늘은 10,11,12강 레츠고

 

 

 

지난 번 Stack: LIFO 이었다. 그럼 큐는? FIFO 안봐도 뻔하쥬

 

바로 문제 풀이하기 전, 파이썬에서 큐를 구현하는 방법 3가지를 살펴보자.

1. list: 가능하지만 비추천

2. collections.deque: 데이터 양방향 추가 가능

3. queue.Queue: 방향성 X. 주로 멀티스레드 환경에서 사용. Locking 지원.

 

 

간단히 소개해주는 블로그:  파이썬에서 큐(queue) 자료구조 사용하기 | Engineering Blog by Dale Seo 

 

파이썬에서 큐(queue) 자료구조 사용하기

Engineering Blog by Dale Seo

www.daleseo.com

 

 

18258번: 큐 2

 

풀이

from queue import Queue

R = int(input())

queue = Queue()

for r in range(R):
    cmd = input()

    if cmd.startswith("push"):
        queue.put(cmd.split()[1])
    elif cmd == "pop":
        if not queue.empty():
            print(queue.get_nowait())
        else:
            print(-1)
    elif cmd == "size":
        print(queue.qsize())
    elif cmd == "empty":
        if queue.empty():
            print(1)
        else:
            print(0)
    elif cmd == "front":
        if not queue.empty():
            print(queue.queue[0])
        else:
            print(-1)
    elif cmd == "back":
        if not queue.empty():
            print(queue.queue[-1])
        else:
            print(-1)

아 더러워 ^^... 

이전에 deque는 써봤는데 Queue는 안 써봐서 한 번 써봤다. deque가 더 편한 듯

 

 

강사님 풀이

import sys
from collections import deque

N = int(input())

d = deque()

for i in range(N):
    command = sys.stdin.readline()
    command = command.split()

    if command[0] == "push":
        d.append(command[1])

    if command[0] == "pop":
        if len(d) == 0:
            print("-1")
        else:
            print(d.popleft())

    if command[0] == "size":
        print(len(d))

    if command[0] == "empty":
        if len(d) == 0:
            print("1")
        else:
            print(0)

    if command[0] == "front":
        if len(d) == 0:
            print("-1")
        else:
            print(d[0])

    if command[0] == "back":
        if len(d) == 0:
            print("-1")
        else:
            print(d[-1])

sys.stdin.readline 편하고 좋구만.

 

 

 

2164번: 카드2

풀이

from collections import deque

n = int(input())

d = deque()
d.extend(list(range(1, n+1)))

while not len(d) == 1:
    d.popleft()
    element = d.popleft()
    d.append(element)

print(d[0])

 

 

강사님 풀이

from collections import deque

N = int(input())

d = deque(list(range(1, N+1)))

drop = True

while len(d) > 1:
    if drop:
        d.popleft()
        drop = False
    else:
        x = d.popleft()
        d.append(x)
        drop = True

print(d[0])

 

오.. 나도 잘 풀었다고 생각했는데, 강사님 코드가 더 낫네.

 

1. 더 직관적인 조건문 len(d) > 1

2. 나는 매 반복마다 popleft()를 실행했지만, 여기는 drop 변수를 사용해서 popleft() 를 한 번만 실행.

 

하지만 여기도 하나 개선 가능한 점

deque(list(range(1, N+1)) 보다 deque(range(1, N+1)) 로 바로 초기화 가능함

 

 

https://abit.ly/lisbva

 

Abit.ly 다운받기

 

abit.ly

 

 

#패스트캠퍼스 #환급챌린지 #패스트캠퍼스후기 #습관형성 #직장인자기계발 #오공완

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함