๐Ÿ“– Coding Study/Algorithm

๋ฐฑ์ค€ 10828 "์Šคํƒ" ํŒŒ์ด์ฌ ๋ฌธ์ œํ’€์ด

๊ณต๋ถ€๋ชปํ•จ 2024. 3. 8. 19:15

์ง€๋‚œํ•™๊ธฐ ์ˆ˜๊ฐ•ํ–ˆ๋˜ ์ž๋ฃŒ๊ตฌ์กฐ ๊ฐ•์˜์—์„œ ๋ฐฐ์šด ๋‚ด์šฉ์„ ์ด์šฉํ•˜์—ฌ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•ด๋ณด์•˜๋‹ค

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

 

LIST