๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

baekjoon. ์Šคํƒ (10828) [python][Silver IV]

ttoance 2023. 1. 16. 23:34

๋ฌธ์ œ ๋งํฌ : https://www.acmicpc.net/problem/10828

 

 

 

๋ฌธ์ œํ’€์ด 

import sys

stack = [] # stack = array : ๋ณต์žกํ•˜๊ฒŒ ํด๋ž˜์Šค๋กœ ๋งŒ๋“ค ํ•„์š” ์—†๋‹ค 
def push(data):
  stack.append(data)

def pop():
  if (empty()):
    print(-1)
  else:
    lastIndex = len(stack) -1
    print(stack.pop(lastIndex)) # remove (value), pop (index)

def size():
  print(len(stack))

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

def top():
  if (empty()):
    print(-1)
  else:
    lastIndex = len(stack) -1
    print(stack[lastIndex])

# ๋ช…๋ น์–ด ์ˆ˜ ๋ฐ›๊ธฐ 
num = int(sys.stdin.readline()) #input ์‚ฌ์šฉํ•  ์‹œ ์‹œ๊ฐ„ ์ดˆ๊ณผ 
for i in range(num):
  str = sys.stdin.readline()
  strArray = str.split()

  command = strArray[0]
  if len(strArray) > 1:
    args = strArray[1]

  if (command == 'push'):
    push(args)
  elif (command == 'pop'):
    pop()
  elif (command == 'size'):
    size()
  elif (command == 'empty'):
    print(empty())
  elif (command == 'top'):
    top()

 


 

[1] python์—์„œ stack์€ list ํ˜•ํƒœ๋กœ ๊ตฌํ˜„๊ฐ€๋Šฅํ•˜๋‹ค. 

ใ„ด ๊ณต์‹๋ฌธ์„œ : https://docs.python.org/ko/3/tutorial/datastructures.html

> list.append(x)

๋ฆฌ์ŠคํŠธ์˜ ๋์— ํ•ญ๋ชฉ์„ ๋”ํ•ฉ๋‹ˆ๋‹ค. a[len(a):] = [x] ์™€ ๋™๋“ฑํ•ฉ๋‹ˆ๋‹ค.

> list.remove(x)

๋ฆฌ์ŠคํŠธ์—์„œ ๊ฐ’์ด x ์™€ ๊ฐ™์€ ์ฒซ ๋ฒˆ์งธ ํ•ญ๋ชฉ์„ ์‚ญ์ œํ•ฉ๋‹ˆ๋‹ค. ๊ทธ๋Ÿฐ ํ•ญ๋ชฉ์ด ์—†์œผ๋ฉด ValueError๋ฅผ ์ผ์œผํ‚ต๋‹ˆ๋‹ค.

> list.pop([i])

๋ฆฌ์ŠคํŠธ์—์„œ ์ฃผ์–ด์ง„ ์œ„์น˜์— ์žˆ๋Š” ํ•ญ๋ชฉ์„ ์‚ญ์ œํ•˜๊ณ , ๊ทธ ํ•ญ๋ชฉ์„ ๋Œ๋ ค์ค๋‹ˆ๋‹ค. ์ธ๋ฑ์Šค๋ฅผ ์ง€์ •ํ•˜์ง€ ์•Š์œผ๋ฉด, a.pop() ์€ ๋ฆฌ์ŠคํŠธ์˜ ๋งˆ์ง€๋ง‰ ํ•ญ๋ชฉ์„ ์‚ญ์ œํ•˜๊ณ  ๋Œ๋ ค์ค๋‹ˆ๋‹ค. (๋ฉ”์„œ๋“œ ์‹œ๊ทธ๋‹ˆ์ฒ˜์—์„œ i ๋ฅผ ๋‘˜๋Ÿฌ์‹ผ ๋Œ€๊ด„ํ˜ธ๋Š” ๋งค๊ฐœ๋ณ€์ˆ˜๊ฐ€ ์„ ํƒ์ ์ž„์„ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค. ๊ทธ ์œ„์น˜์— ๋Œ€๊ด„ํ˜ธ๋ฅผ ์ž…๋ ฅํ•ด์•ผ ํ•œ๋‹ค๋Š” ๋œป์ด ์•„๋‹™๋‹ˆ๋‹ค. ์ด ํ‘œ๊ธฐ๋ฒ•์€ ํŒŒ์ด์ฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋ ˆํผ๋Ÿฐ์Šค์—์„œ ์ง€์ฃผ ๋“ฑ์žฅํ•ฉ๋‹ˆ๋‹ค.)

์ฐธ๊ณ ๋กœ, remove์•ˆ์—๋Š” ์ธ์ž๊ฐ’์œผ๋กœ ๊ฐ’์ž์ฒด๋ฅผ, pop์€ ์ธ์ž๊ฐ’์œผ๋กœ ์ธ๋ฑ์Šค๋ฅผ ๋„ฃ๊ธฐ ๋•Œ๋ฌธ์— pop์„ ํ™œ์šฉํ•ด์„œ ๊ตฌํ˜„ํ•ด์•ผ ํ•œ๋‹ค. ์ด ๋ถ€๋ถ„ ๋ฌธ์„œ๋ฅผ ์ œ๋Œ€๋กœ ์•ˆ ์ฝ์–ด์„œ ์กฐ๊ธˆ ๋” ์‹œ๊ฐ„์ด ๊ฑธ๋ ธ๋‹ค. 

 

[2] ์‹œ๊ฐ„ ์ œํ•œ ์ดˆ๊ณผ๊ฐ€ ๋‚˜๋ฉด, input() ๋Œ€์‹  sys.stdin.readline()์„ ํ™œ์šฉํ•˜๋ฉด ์‹œ๊ฐ„์ด ์ค„์–ด๋“ ๋‹ค. 

๋ฐ˜์‘ํ˜•