-
[백준 파이썬] 스택 - 10828번: 스택알고리즘/백준 2021. 3. 28. 22:48
백준 10828번. 스택 간단한 스택 문제이다. 특정 명령을 받았을 때 스택에 대한 명령을 수행한다.
처음 생각해본건 case 별로 조건문을 넣으면 될 것 같아 코드를 작성해 보았다.
n = int(input()) order_list = [] for i in range(n): order_list.append(input()) stack = [] for order in order_list: if order.startswith('push'): order, number = order.split() stack.append(int(number)) elif order == "pop": if len(stack) == 0: print(-1) else: print(stack.pop()) elif order == "size": print(len(stack)) elif order == "empty": if len(stack) == 0: print(1) else: print(0) elif order == "top": if len(stack) == 0: print(-1) else: print(stack[-1])
order_list : 입력해주는 명령을 저장하는 리스트
stack : push와 pop을 수행할 스택
실행결과 정상적으로 출력은 되었으나 해당 코드 제출시 시간초과 오류가 났다.
시간 초과 시 sys 모듈을 이용하면 해결되는 경우가 있다고 해서 해당 코드를 넣어 보았다.
import sys input = sys.stdin.readline n = int(input()) print(n) order_list = [] for i in range(n): order_list.append(input().strip()) print(order_list) stack = [] for order in order_list: if order.startswith('push'): order, number = order.split() stack.append(int(number)) elif order == "pop": if len(stack) == 0: print(-1) else: print(stack.pop()) elif order == "size": print(len(stack)) elif order == "empty": if len(stack) == 0: print(1) else: print(0) elif order == "top": if len(stack) == 0: print(-1) else: print(stack[-1])
성공적으로 제출이 되었다!
sys.stdin.readline의 경우 \n를 지우지 않고 prompt message를 포함하지 않고 출력하기 때문에 input()에 비해 빠르다.
prompt message 란
input("값을 입력하시오: ")
와 같이 input의 경우 출력되는 메세지를 설정해줄 수 있고 이때 이 메세지를 prompt message라고 한다.
input = sys.stdin.readline 으로 할 필요 없이 n = int(sys.stdin.readline()) 으로 바로 넣어줘도 된다. (괄호 유무 주의!)
주의할점은 문자열을 입력할시 뒤에 \n 이 붙게 되므로 .strip() 을 통해 지워주어야 한다.