알고리즘 공부

[파이썬] 백준 10828 - 스택

Developer KTU 2021. 3. 5. 15:46
반응형

기본적인 스택 자료구조와 함수의 기본적인 사용법을 알고있는지 테스트해보는 문제인 것 같다.

< 나의 코드 >

import sys


def stack_push(stack, X):
    stack.append(X)


def stack_pop(stack):
    if len(stack) == 0:
        return -1
    elif len(stack) != 0:
        last = stack.pop()
        return last


def is_empty(stack):
    if len(stack) == 0:
        return 1
    else:
        return 0


def check_size(stack):
    size = len(stack)
    return size


def is_top(stack):
    if len(stack) == 0:
        return -1
    else:
        top = stack[-1]
        return top

N = int(sys.stdin.readline())
stack = []

for i in range(N):
    input_order = sys.stdin.readline().split()
    order = input_order[0]
    if order == "push":
        stack_push(stack, int(input_order[1]))
    elif order == "pop":
        last = stack_pop(stack)
        print(last)
    elif order == "size":
        size = check_size(stack)
        print(size)
    elif order == "empty":
        empty = is_empty(stack)
        print(empty)
    elif order == "top":
        top = is_top(stack)
        print(top)

< 시행착오 >

처음 문제를 풀고 제출했을때 런타임에러 (Index Error)가 나왔다. Index Error가 정확히 어디서 나온지 몰라서 헤맸다.

<해결방법>

원인은 is_top 함수에서 stack 리스트 가장 마지막 요소를 참조할때 else 문에 넣지 않고 is_top 함수 가장 위에 선언했다. 이런 경우는 stack 리스트가 비어있다면 비어있는 리스트의 가장 마지막 요소를 참조하므로 런타임에러 (Index Error)가 뜬다.

 

★ 중요

스택은 기본적인 자료구조 중 하나로서 LIFO 구조이다. (Last-In-First-Out)

반응형