Hoplin 2022. 1. 18. 13:34
반응형

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

 

10828번: 스택

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

www.acmicpc.net

기본적인 스택을 구현하는 문제이다. 조금 이상하게 풀어보고싶다는 이상한 생각이 들어 이상하게 풀어봤다.

import re
import sys

class Stack(object):
    def __init__(self) -> None:
        self.stack = []
    
    def push(self,x) -> None:
        self.stack.append(x)
    
    def pop(self) -> int:
        #스택이 비은 경우에는 -1 출력
        if self.empty():
            return -1
        return self.stack.pop()
    
    def size(self) -> int:
        return len(self.stack)
    
    def empty(self) -> bool:
        #스택이 비어있으면 1을
        if not self.stack:
            return 1
        #비어있지 않으면 0을 출력
        else:
            return 0
        
    def top(self) -> int:
        if self.empty():
            return -1
        return self.stack[len(self.stack) - 1]


if __name__ == "__main__":
    stk = Stack()
    commands = {
        "push" : stk.push,
        "pop" : stk.pop,
        "size" : stk.size,
        "empty" : stk.empty,
        "top" : stk.top
    }
    result = []
    for _ in range(int(sys.stdin.readline())):
        val = sys.stdin.readline().split()
        if len(val) == 1:
            execute = commands[val[0]]()
            if execute != None:
                result.append(execute)
        else:
            command, value = val
            execute = commands[command](value)
            if execute != None:
                result.append(execute)
    
    print(*result,sep = "\n")
반응형