문제풀이

collections 라이브러리를 이용하면 간단히 풀 수 있는 문제다.

입력 받을 때 input()으로 하면 시간 초과가 나온다.

sys.stdin.readline()으로 풀면 된다.

 

- 데크가 빈 경우를 식별하기 위한 조건문을 사용할 때는 len()를 통해 비교하지 말고, 데크를 가르키고 있는 인스턴트 변수의 존재 유무를 판별하는 것이 합리적이다.

코드

import sys
from collections import deque
# sys.stdin = open("C:/Users/JIn/PycharmProjects/coding_Test/input.txt", "rt")

t = int(sys.stdin.readline())
dq = deque()
for _ in range(t):
    cmd = sys.stdin.readline().strip()
    if cmd == "front":
        if dq:
            print(dq[0])
        else:
            print(-1)
    elif cmd == "back":
        if dq:
            print(dq[-1])
        else:
            print(-1)
    elif cmd == "size":
        print(len(dq))
    elif cmd == "empty":
        if dq:
            print(0)
        else:
            print(1)
    elif cmd == "pop_front":
        if dq:
            print(dq.popleft())
        else:
            print(-1)
    elif cmd == "pop_back":
        if dq:
            print(dq.pop())
        else:
            print(-1)
    else:
        cmd, x = cmd.split(" ")
        if cmd == "push_back":
            dq.append(x)
        else:  # push_front
            dq.appendleft(x)

+ Recent posts