๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/๋ฐฑ์ค€(BOJ)

[ ํŒŒ์ด์ฌ(python) ] ๋ฐฑ์ค€ 10828 - ์Šคํƒ

by YWTechIT 2021. 5. 4.
728x90

๐Ÿ“ ๋ฐฑ์ค€ 10828 - ์Šคํƒ

๋ฌธ์ œ: ๋ฐฑ์ค€ 10828 - ์Šคํƒ


๐Ÿ’ก ๋‚˜์˜ ํ’€์ด

3๊ฐœ์›” ์ „ ์ด ๋ฌธ์ œ๋ฅผ ๋ดค์„ ๋•Œ๋Š” ๋ชป ํ’€์—ˆ๋Š”๋ฐ ์ง€๊ธˆ์€ ํ’€๊ฒŒ ๋œ ๋ฌธ์ œ๋‹ค. ๊ทธ๋•Œ๋Š” ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ๋”ฐ๋กœ ๋งŒ๋“œ๋Š”์ง€ ๋ชฐ๋ž์—ˆ๋Š”๋ฐ... (์ถ”์–ต ๋‹์Œ)

 

๋ฌธ์ œํ’€์ด๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

  1. ๊ฐ ๊ธฐ๋Šฅ๋ณ„๋กœ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ ๋‹ค.
  2. n๋งŒํผ ์ž…๋ ฅ์„ ๋ฐ›๋Š”๋ฐ, ์ž…๋ ฅ์ด ํ•จ์ˆ˜์˜ ์ด๋ฆ„์— ํฌํ•จ๋˜๋ฉด ํ•ด๋‹น ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰์‹œํ‚จ๋‹ค.

์ฐธ๊ณ ๋กœ ํ•จ์ˆ˜์•ˆ์— if, else๋ฌธ์„ ์‚ฌ์šฉํ•ด๋„ ๋˜๋Š”๋ฐ else๋ฅผ ๋นผ๊ณ  return๋ฌธ์„ ์ง‘์–ด๋„ฃ์—ˆ๋‹ค. if๋ฌธ ์ง€๋‚˜ ์กฐ๊ฑด์„ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•œ ๊ธฐ๋Šฅ๋งŒ ๋‚จ์•„ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ return์„ ๋งŒ๋‚˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ๋˜, push ๊ฐ’์€ split()์œผ๋กœ ๋‚˜๋ˆ  [1]๋ฒˆ์งธ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

import sys
input = sys.stdin.readline

n = int(input())
stack = []

def push(x):
    stack.append(x)

def pop():
    if not stack:
        return -1
    return stack.pop()

def size():
    return len(stack)

def empty():
    if not stack:
        return 1
    return 0

def top():
    if not stack:
        return -1
    return stack[-1]

for _ in range(n):
    command = input().split()
    if 'push' in command:
        push(command[1])
    elif 'top' in command:
        print(top())
    elif 'size' in command:
        print(size())
    elif 'empty' in command:
        print(empty())
    else:
        print(pop())
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€