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
- 오블완
- Laravel
- 99클럽
- DP
- 백준
- til
- 코딩테스트 준비
- 코테 파이썬
- vue
- 티스토리챌린지
- 코테
- 라라벨
- 코딩테스트준비
- 개발자취업
- 코딩테스트
- react
- 항해99
- 뷰
- 알고리즘
- c++ 코테
- 플러터
- flutter getx
- 파이썬 코테
- 개발자 취업
- C++
- ML
- 파이썬
- Flutter
- 안드로이드
Archives
- Today
- Total
잡다로그
[Python/코테] 백준 10828 스택 본문
10828 스택
문제 및 조건 설명: https://www.acmicpc.net/problem/10828


import sys
n = int(sys.stdin.readline())
stack = []
for i in range(n):
command = sys.stdin.readline().split()
if (command[0] == "push"):
stack.append(int(command[1]))
# pos += 1
elif (command[0] == "pop"):
if (len(stack) != 0):
print(stack.pop())
else:
print(-1)
elif (command[0] == "top"):
if (len(stack) != 0):
print(stack[-1])
else:
print(-1)
elif (command[0] == "size"):
print(len(stack))
elif (command[0] == "empty"):
if (len(stack) != 0):
print(0)
else:
print(1)
나다어
- 코테는 개발과 다르다. 변수를 담아 쓸 생각보다는 바로바로 이용할 생각을 하자. 한 케이스에서만 쓰이면 굳이 변수 설정할 필요도 없음(command[1]과 같이)
- 입력의 갯수가 다를 때에는 split() 함수를 이용한다.
또는 직접 배열을 append, pop하지 않고 인덱스 변수를 사용해서 구현할 수 있다.
그러나 인덱스 변수를 사용하려면, out of range오류가 발생하지 않기 위해서 stack을 미리 초기화해두어야 하는데, 이는 메모리 비효율을 불러일으킬 수 있다.
import sys
n = int(sys.stdin.readline())
stack = [0] * n
pos = 0
for i in range(n):
command = sys.stdin.readline().split()
func = command[0]
if (func == "push"):
stack[pos] = int(command[1])
pos += 1
elif (func == "pop"):
if (pos != 0):
print(stack[pos-1])
pos -= 1
else:
print(-1)
elif (func == "top"):
if (pos != 0):
print(stack[pos-1])
else:
print(-1)
elif (func == "size"):
print(pos)
elif (func == "empty"):
if (pos != 0):
print(0)
else:
print(1)
'Algorithm' 카테고리의 다른 글
| [Python/코테] 백준 10845번 큐 (0) | 2023.11.09 |
|---|---|
| [C++/코테] 스택(Stack) 기초 (0) | 2023.11.08 |
| [Python/코테] 백준 2577번 숫자의 개수 (0) | 2023.11.08 |
| [Python/코테] 백준 28431 양말 짝 맞추기 (0) | 2023.11.08 |
| [Python/코테] 백준 2480번 주사위 세 개 (0) | 2023.11.08 |
Comments