노누리·2022년 6월 30일
0

문제

정수를 저장하는 덱(Deque)를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.

명령은 총 여덟 가지이다.

  • push_front X: 정수 X를 덱의 앞에 넣는다.
  • push_back X: 정수 X를 덱의 뒤에 넣는다.
  • pop_front: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • pop_back: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • size: 덱에 들어있는 정수의 개수를 출력한다.
  • empty: 덱이 비어있으면 1을, 아니면 0을 출력한다.
  • front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
  • back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.

입력

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.

출력

출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.

예제 입력 1

15
push_back 1
push_front 2
front
back
size
empty
pop_front
pop_back
pop_front
size
empty
pop_back
push_front 3
empty
front

예제 출력 1

2
1
2
0
2
1
-1
0
1
-1
0
3

예제 입력 2

22
front
back
pop_front
pop_back
push_front 1
front
pop_back
push_back 2
back
pop_front
push_front 10
push_front 333
front
back
pop_back
pop_back
push_back 20
push_back 1234
front
back
pop_back
pop_back

예제 출력 2

-1
-1
-1
-1
1
1
2
2
333
10
10
333
20
1234
1234
20

문제 풀이

시간초과 발생한 풀이

from collections import deque
N=int(input())
queue=deque([])

def size(q):
    return len(q)

def empty(q):
    if size(q)==0:
        return 1
    else:
        return 0

for _ in range(N):
    input_queue=input().split(' ')
    if input_queue[0]=='push_front':
        queue.appendleft(input_queue[1])
    elif input_queue[0]=='push_back':
        queue.append(input_queue[1])
    elif input_queue[0]=='pop_back':
        if empty(queue):
            print(-1)
        else:
            print(queue.pop())
    elif input_queue[0]=='pop_front':
        if empty(queue):
            print(-1)
        else:
            print(queue.popleft())
    elif input_queue[0]=='size':
        print(size(queue))
    elif input_queue[0]=='empty':
        print(empty(queue))
    elif input_queue[0]=='front':
        if empty(queue):
            print(-1)
        else:
            print(queue[0])
    elif input_queue[0]=='back':
        if empty(queue):
            print(-1)
        else:
            print(queue[-1])

이전에 풀었던 큐 문제와 비슷한 문제였다. 대신 push_front와 같이 큐의 앞부분에 값을 넣는다던지 큐의 뒷부분을 pop하는 명령이 추가되었다.

시간초과가 발생할 것을 고려하여 deque를 이용하여 큐를 구성하였는데도 불구하고 시간초과가 발생했다.

if문을 줄일수는 없었기 때문에 input을 고쳐보기로 하고 import sys를 이용하여 시간초과를 방지했다.

성공한 풀이

from collections import deque
import sys
input=sys.stdin.readline

N=int(input())
queue=deque([])

def size(q):
    return len(q)

def empty(q):
    if size(q)==0:
        return 1
    else:
        return 0

for _ in range(N):
    input_queue=input().split()
    if input_queue[0]=='push_front':
        queue.appendleft(input_queue[1])
    elif input_queue[0]=='push_back':
        queue.append(input_queue[1])
    elif input_queue[0]=='pop_back':
        if empty(queue):
            print(-1)
        else:
            print(queue.pop())
    elif input_queue[0]=='pop_front':
        if empty(queue):
            print(-1)
        else:
            print(queue.popleft())
    elif input_queue[0]=='size':
        print(size(queue))
    elif input_queue[0]=='empty':
        print(empty(queue))
    elif input_queue[0]=='front':
        if empty(queue):
            print(-1)
        else:
            print(queue[0])
    elif input_queue[0]=='back':
        if empty(queue):
            print(-1)
        else:
            print(queue[-1])

import sys를 하고 input=sys.stdin.readline을 이용하여 입력을 받으니 시간초과가 사라졌다. 하지만 이때 틀렸던 부분이 있었는데 for문 내에서 입력을 받을때 split(' ')을 했더니 풀이가 틀렸다고 떴다.

알고 보니 sys.stdin.readline()은 마지막에 공백문자가 들어가서 입력값이 다르게 받아지는 문제였는데 이를 해결하는데 두가지 방법이 있었다.

  1. for문내에서 입력을 받을 때 input().split()으로 고친다.
  2. for문내에서 입력을 받을 때 input().strip().split()을 이용하여 공백문자를 없애준다.

시간초과가 발생할때 입력방법을 sys.stdin.readline()으로 바꾸는 것은 알았는데 공백문자를 제거하는 것은 생각하지 못했다. 매번 input()을 이용했더니 생각하지 못한 것들은 하나씩 놓치는 것 같다. 여러가지 방법을 자주 써보면서 적응해야할 것 같다.

profile
백엔드 개발자입니다.

0개의 댓글