본문 바로가기

코딩 테스트/백준

[Python] 백준 28278 스택 2

실버4

문제

 

문제 분석

  • n : 몇번 stack 함수를 불러올 것인가(예고)
  • 이후 조건에 따른 값들이 주어진다.

 

코드 설계

  • 파이썬에서는 스택 자료구조를 제공하지 않는다. 따라서 파이썬의 스택 = list
  • 스택은 한쪽 끝에서만 자료를 넣거나 뺄 수 있는 자료구조 (LIFO : Last In First Out)
  • push() : 스택에 원소 추가
  • pop() : 스택 가장 위에 있는 원소를 삭제하고 그 원소를 반환
  • peek() : 스택 가장 위에 있는 원소를 반환하지만 삭제는 x
  • empty() : 스택이 비어있다면 1, 아니면 0 반환

 

1차

n = int(input())

stack = []
def stack_func(num):
    if num == 1:
        x = int(input())
        stack.push(x)
    if num == 2 :
        if stack.empty():
            print(-1)
        else :
            print(stack.pop())
    if num == 3:
        print(len(stack))
    if num == 4 :
        if stack :
            print(1)
        else :
            print(0)
    if num == 5 :
        if stack:
            print(-1)
        else:
            print(stack.peek()) # stack[-1] 도 가능

for _ in range(n):
    num = int(input())
    stack_func(num)
  • 스택을 넣을 때는 입력 값이 또 필요하다. > 이걸 고려해서 저렇게 한건데 역시나 안된다.
  • 그리고 계속 if가 아니라 이후는 elif.. 정신차려..
  • 그래서 입력받을 때 값을 배열로 받는다. (띄어쓰기, 행바꿈 고려)
  • 해당 줄에 대한 값을 다 받고, '1'일때만 push

 

2차

n = int(input()) # n = int(sys.stdin.readline())

stack = []

for _ in range(n):
    command = input().split()
    # command = list(map(int, input().split()))

    if command[0] == '1' :
        stack.append(command[1])
    elif command[0] == '2' :
        if stack : # stack 안에 값이 있다면 자동으로 true. empty()를 따로 안해줘도 된다.
            print(stack.pop())
        else :
            print(-1)
    elif command[0] == '3' :
        print(len(stack))
    elif command[0] == '4' :
        if stack :
            print(0)
        else :
            print(1)
    elif command[0] == '5' :
        if stack :
            print(stack[-1])
        else :
            print(-1)
  • 여기서 또 그냥 input()으로 입력을 받았더니 시간초과..

 

3차

import sys
input = sys.stdin.readline

n = int(input())

stack = []

for _ in range(n):
    command = input().split()
    # command = list(map(int, input().split())) # map을 사용한 후 list로 변환해야 인덱싱이 가능함

    if command[0] == '1' :
        stack.append(command[1])
    elif command[0] == '2' :
        if stack : # stack 안에 값이 있다면 자동으로 true. empty()를 따로 안해줘도 된다.
            print(stack.pop())
        else :
            print(-1)
    elif command[0] == '3' :
        print(len(stack))
    elif command[0] == '4' :
        if stack :
            print(0)
        else :
            print(1)
    elif command[0] == '5' :
        if stack :
            print(stack[-1])
        else :
            print(-1)

+)

command = list(map(int, input().split()))

command 값을 받는다면 문자열이 아닌 정수로 입력을 받게 된다.

command[0] == 1

따라서 command[0] == '1'처럼 문자열과 비교하는 대신, 정수로 비교해야 하기 때문에 command[0] == 1로 비교할 수 있다.

(이때 또 까먹고 놓친거는 map을 사용한 후 list로 변환을 해줘야 인덱싱이 가능하다..)

 

 

스택 개념 관련 REFERENCE

https://velog.io/@yeseolee/Python-%EC%9E%90%EB%A3%8C%EA%B5%AC%EC%A1%B0-%EC%8A%A4%ED%83%9DStack