sooleeandtomas

[day5] 백준 10828번 - 스택 스택 (python) (feat. 파이썬 sys.stdin.readline()) 본문

코딩테스트 알고리즘/스택

[day5] 백준 10828번 - 스택 스택 (python) (feat. 파이썬 sys.stdin.readline())

sooleeandtomas 2022. 9. 29. 22:47

https://www.acmicpc.net/problem/10828

 

import sys

def stack(n):
  stack_list = []
  for _ in range(n):
    command = sys.stdin.readline() #input() 을 사용하게 되면 시간이 초과된다.

    if "push" in command:
      number = command.split(' ')[-1]
      stack_list.append(int(number))
    if "top" in command:
      if len(stack_list) == 0:
        print(-1)
      else:
        print(stack_list[-1])
    if "size" in command:
      print(len(stack_list))
    if "pop" in command:
      if len(stack_list) == 0:
        print(-1)
      else:
        print(stack_list.pop())
    if "empty" in command:
      if len(stack_list) == 0:
        print(1)
      else:
        print(0)
      
N = int(sys.stdin.readline())
stack(N)

별로 어려운 문제는 아니지만, input값을 받는데 익숙하지 않았고, 프로그래머스와 UI와 문제 방식에 좀 차이가 있는 것 같아서 헷갈렸다.

모르겠을 때는 다른 사람의 코드를 보는게 최선이다.

 

더 멋있는 코드를 발견했다. 클래스에 메소드를 등록하는 방식이다.

import sys

class stack:
  def __init__(self):
    self.L=[]
  def push(self, X):
    self.L.append(X)

  def pop(self): #self를 넘겨주어야 한다.
    if len(self.L) == 0:
      return -1
    a = self[-1]
    del self.L[-1]
    return a

  def size(self):
    return len(self.L)

  def empty(self):
    if len(self.L) == 0:
      return 1
    return 0

  def top(self):
    if len(self.L) == 0:
      return -1
    return self.L[-1]

a = stack()
N = int(sys.stdin.readline())

for i in range(N):
  L = list(map(str, sys.stdin.readline().strip().split()))
  if len(L) == 2:
    a.push(int(L[1]))
  elif L[0] == 'pop':
    print(a.pop())
  elif L[0] == 'size':
    print(a.size())
  elif L[0] == 'empty':
    print(a.empty())
  elif L[0] == 'top':
    print(a.top())

 

 

 

input과 sys.stdin.readline()의 차이점

command = sys.stdin.readline()
command2 = input()

print(command)
# command
(개행 포함) 

print(command2)
#command
(개행 미포함)

input 내장함수는 입력받은 값의 개행 문자를 삭제시켜서 리턴한다. rstrip()함수를 한번 적용한 후 리턴한다.

반면, stdin.readline은 그대로 리턴한다. 

따라서 어떤 방식으로 input을 받느냐에 따라 시간 차이가 약간 있을 수 있다.

Comments