Problem Solving/BOJ

[BOJ][Python]10828번 풀이

NoiB 2021. 12. 28. 20:04
반응형

https://www.acmicpc.net/problem/10828

 

10828번: 스택

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

www.acmicpc.net

import sys
ssr = sys.stdin.readline

n = int(ssr())
list = []
for i in range(n):
    command = ssr().rstrip()
    if command.find('push') != -1:
        list.append(int(command[4:]))
    elif command == 'pop':
        if len(list) == 0:
            print(-1)
        else:
            print(list.pop())
    elif command == 'size':
        print(len(list))
    elif command == 'empty':
        if len(list) == 0:
            print(1)
        else:
            print(0)
    elif command == 'top':
        if len(list) == 0:
            print(-1)
        else:
            print(list[len(list)-1])

아마 push 부분이 순간적으로 고민이 되셨던 분들이 있으시지 않을까 생각이 드는데요. 저는 슬라이싱을 통해서 구현했습니다. 처음에는 숫자가 한자리수만 올거라고 막연하게 생각하고 구현했다가 틀리길래 push 뒤로 오는 원소들만 int형으로 변환해서 사용했습니다.

반응형