본문 바로가기
해외 주식 도전기

10828번: 스택 [Python]

by 데이터 분석가가 되자 2025. 3. 3.
반응형

 

 

1. 문제 이해

문제 개요

 

● 스택을 구현하고, 여러 명령어를 처리하는 프로그램을 작성해야 합니다.

 

● 스택이란 Last-In-First-Out(LIFO, 후입선출) 구조를 가지는 자료구조입니다.

 

● 입력으로 명령어가 주어지며, 이를 차례로 실행하여 결과를 출력해야 합니다.

 

 

명령어 종류

명령어 동작
push x 정수 x를 스택에 넣는다
pop 스택의 최상단 값을 제거하고 출력 (비어 있으면 -1을 출력한다)
size 현재 스택에 들어있는 정수 개수를 출력한다.
empty 스택이 비어 있으면 1, 아니면 0을 출력한다
top 스택의 최상단 값을 출력 (비어 있으면 -1을 출력한다)

 

 


 

2. 접근 방식

입력 & 출력 방식 최적화

 

● 입력 최적화 :

 

   sys.stdin.readline()을 사용하여 입력 속도를 빠르게 처리합니다.

 

   파이썬의 input()은 속도가 느리기 때문에 대량의 입력을 처리할 때 sys.stdin.readline()을 사용하는 것이 효율적입니다.

 

● 출력 최적화 :

 

   매번 print()를 호출하면 속도가 느려지므로, 결과를 리스트에 저장한 후 한 번에 sys.stdout.write()로 출력합니다.

 

 


 

 

3. 코드 설명

 

def stack_operations(commands):
	stack = []
    result = []

 

stack : 스택을 구현할 리스트

result : 최종 출력을 저장할 리스트

 

명령어 처리 로직

 

for command in commands:

 

 

● 입력받은 명령어를 한 줄씩 처리합니다.

 

 

push x 처리

 

if command.startswith("push"):
	-, value = command.split()
    stack.append(int(value))

 

 

■ push x는 x 값을 스택에 추가하는 명령입니다.

 

■ split()을 사용하여 push와 x를 분리한 뒤, x를 정수형으로 변환하여 stack.append()를 이용해 리스트에 추가합니다.

 

 

pop 처리

 

elif command == "pop":
	result.append(stack.pop() if stack else -1)

 

■ 스택이 비어있지 않으면 .pop()을 이용해 최상단 값을 제거하고 출력합니다.

 

■ 비어 있다면 -1을 출력합니다.

 

 

size 처리

 

elif command == "size":
	result.append(len(stack))

 

■ 스택의 크기 (len(stack))를 출력합니다.

 

 

empty 처리

 

elif command == "empty":
	result.append(0 if stack else 1)

 

■ 스택이 비어있으면 1, 그렇지 않으면 0을 출력합니다.

 

 

top 처리

 

elif command == "top":
	result.append(stack[-1] if stack else -1)

 

■ 스택이 비어있지 않다면 stack[-1] (맨 위의 값)을 출력합니다.

 

■ 스택이 비어 있다면 -1을 출력합니다.

 

 

메인 실행부

 

if __name__ == "__main__":
	n = int(sys.stdin.readline().strip()) # 첫 줄 명령어 개수
    commands = [sys.stdin.readline().strip() for _ in range(n)] # 명령어 리스트

 

 

■ 첫 번째 입력값 n은 명령어 개수, 이후 n개의 명령어를 리스트 commands에 저장합니다.

 

 

results = stack_operations(commands)
sys.stdout.write("\n".join(map(str, results)) + "\n")

 

 

■ stack_operations(commands) 함수를 호출하여 결과 리스트를 얻습니다.

 

■ sys.stdout.write() 를 사용하여 \n으로 연결된 문자열을 한 번에 출력합니다.

   이는 매번 print() 를 호출하는 것보다 빠른 방법입니다.

 

 

총 코드

 

import sys

def stack_operations(commands):
    stack = []
    result = []
    
    for command in commands:
        if command.startswith("push"):
            _, value = command.split()
            stack.append(int(value))
        elif command == "pop":
            result.append(stack.pop() if stack else -1)
        elif command == "size":
            result.append(len(stack))
        elif command == "empty":
            result.append(0 if stack else 1)
        elif command == "top":
            result.append(stack[-1] if stack else -1)
    
    return result

if __name__ == "__main__":
    n = int(sys.stdin.readline().strip())
    commands = [sys.stdin.readline().strip() for _ in range(n)]
    
    results = stack_operations(commands)
    
    sys.stdout.write("\n".join(map(str, results)) + "\n")