Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- 코딩테스트
- 백준 스택 시간초과 python
- javascript
- next Link
- 스택
- Android
- 파이썬
- 백준 스택
- 알고리즘
- kotlin
- firebase
- 프론트엔드
- 안드로이드
- stdin vs input
- JS
- 최적화
- 자바스크립트
- 파이어베이스
- NPM
- Python
- 타입스크립트
- HTML
- typescript
- C++
- k for k
- TS
- CSS
- 리액트
- react
- nodejs
Archives
- Today
- Total
sooleeandtomas
[day5] 백준 10828번 - 스택 스택 (python) (feat. 파이썬 sys.stdin.readline()) 본문
코딩테스트 알고리즘/스택
[day5] 백준 10828번 - 스택 스택 (python) (feat. 파이썬 sys.stdin.readline())
sooleeandtomas 2022. 9. 29. 22:47
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을 받느냐에 따라 시간 차이가 약간 있을 수 있다.
'코딩테스트 알고리즘 > 스택' 카테고리의 다른 글
[day14] 백준 9093번 스택 (단어 뒤집기) python (0) | 2022.10.11 |
---|---|
[day6] 백준 1874번 스택 수열 (Python) (1) | 2022.10.01 |
[day5] 백준 - 스택 제로 (python) (0) | 2022.09.29 |
[day1] 코딩테스트 알고리즘 - 스택 (올바른 괄호) (0) | 2022.09.26 |
Comments