์ง๋ํ๊ธฐ ์๊ฐํ๋ ์๋ฃ๊ตฌ์กฐ ๊ฐ์์์ ๋ฐฐ์ด ๋ด์ฉ์ ์ด์ฉํ์ฌ ์ฝ๋๋ฅผ ์์ฑํด๋ณด์๋ค
stack = []
high = -1
def push(num) :
global high
stack.append(num)
high += 1
def top() :
if len(stack) == 0 :
print(-1)
else :
print(stack[high])
def userDefPop() :
global high
if high == -1 :
print(-1)
else :
print(stack.pop())
high -= 1
n = int(input())
for _ in range(n):
command = input()
if "push" in command :
command = command.split()
push(command[1])
if command == "top" :
top()
if command == "size" :
print(len(stack))
if command == "pop" :
userDefPop()
if command == "empty" :
print(1) if high == -1 else print(0)
์์ ๊ทธ๋๋ก ์ ๋ ฅํด๋ณด๊ณ ์ถ๋ ฅ์ด ๋์ผํ๊ฒ ๋์ค๋ ๊ฒ์ ํ์ธํ ํ ์ ์ถํ์์ผ๋, ์๊ฐ ์ด๊ณผ๋ผ๋ ๊ฒฐ๊ณผ์ ํจ๊ป ์คํจํ๋ค.
์ง๋ฌธ ๊ฒ์ํ์ ๋๋ฌ๋ณด๋ค๊ฐ input() ํ์์ผ๋ก๋ง ์ฌ์ฉํ๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋ ์ ์๋ค๋ ๊ธ์ ๋ณด๊ฒ ๋์๋ค.
๊ด๋ จํ์ฌ ๊ฒ์ํด๋ณด๋, ์ ์ถ๋ ฅ ์๋๋ฅผ ๋น ๋ฅด๊ฒ ํ๊ธฐ ์ํด์๋
import sys
input = sys.stdin.readline
์ด ์ฝ๋๋ฅผ ์จ์ฃผ๋ ๊ฒ์ด ์ข๋ค๊ณ ํ๋ค.
๋ค๋ง ์ ์ํด์ผ ํ ์ ์ ์ ์ฝ๋๊ฐ ์ ์ฉ๋ input์ ๊ฐํ๋ฌธ์๊น์ง ์ฝ์ด๋ค์ด๊ธฐ ๋๋ฌธ์ .rstrip()๋ฑ์ ์ด์ฉํ์ฌ ๊ฐํ๋ฌธ์๋ฅผ ์ง์์ฃผ์ด์ผ ํ๋ค๋ ๊ฒ์ด๋ค.
์๋๋ ์์ ๋ ์ฝ๋์ด๋ค
import sys
input = sys.stdin.readline
stack = []
high = -1
def push(num) :
global high
stack.append(num)
high += 1
def top() :
if len(stack) == 0 :
print(-1)
else :
print(stack[high])
def userDefPop() :
global high
if high == -1 :
print(-1)
else :
print(stack.pop())
high -= 1
n = int(input().rstrip())
for _ in range(n):
command = input().rstrip()
if "push" in command :
command = command.split()
push(command[1])
if command == "top" :
top()
if command == "size" :
print(len(stack))
if command == "pop" :
userDefPop()
if command == "empty" :
print(1) if high == -1 else print(0)

์ฐธ๊ณ
https://urakasumi.tistory.com/273
[ Python ] ์ ์ถ๋ ฅ(I/O) ์๋ ๋น ๋ฅด๊ฒ ํ๊ธฐ
๋ฐฑ์ค ํ์ด์ฌ ๋ฌธ์ ๋ฅผ ํ๋ค๋ณด๋ฉด ์๊ฐ์ด๊ณผ๊ฐ ๋จ๋ ๊ฒฝ์ฐ ์ ์ถ๋ ฅ ๋ฐฉ๋ฒ์ ๋ฐ๊ฟ์ค์ผ๋ก์จ ํด๊ฒฐํ๋ ๋ฐฉ๋ฒ์ด ์๋ค. import sys input = sys.stdin.readline print = sys.stdout.write ์ ์ฒ๋ผ input()๊ณผ print()๋ฅผ ๋ฎ์ด์์๋ฒ๋ฆฐ
urakasumi.tistory.com
'๐ Coding Study > Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
์ฝ๋ ์คํ ์๊ฐ ๋จ์ถ "ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);" (1) | 2024.01.01 |
---|---|
๋ฐฑ์ค 10952๋ฒ ๋ฌธ์ ํ์ด (0) | 2024.01.01 |