Part4.4_자료구조(스택,큐,해쉬,힙)_후위식 연산

Eugenius1st·2022년 1월 17일
0

Python_algorithm

목록 보기
20/83

후위식 연산

내가 생각한 코드

import sys
sys.stdin = open("input.txt", "rt")

a = input()
stack = []
calNum=0
for x in a:
    if x.isdecimal():
        stack.append(int(x))
    else:
        tmp = stack.pop()
        calNum = stack.pop()
        if x == '+':
            calNum = calNum + tmp
        elif x == '-':
            calNum = calNum - tmp
        elif x == '*':
            calNum = calNum * tmp
        else:
            calNum = calNum / tmp
        stack.append(calNum)
print(calNum)

선생님 코드

import sys
sys.stdin = open("input.txt", "rt")

a = input()
stack = []

for x in a:
    if x.isdecimal():
        stack.append(int(x))
    else:
        n1 = stack.pop()
        n2 = stack.pop()
        if x == '+':
            stack.append(n2+n1)
        elif x == '-':
            stack.append(n2-n1)
        elif x == '*':
            stack.append(n1*n2)
        else:
            stack.append(n2/n1)    
print(stack[0])

한 2줄 더 줄이셨네;; 이정도는 유진아 너도 생각할 수 있지 않니?

profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글