본문 바로가기

algorithm

알고리즘 기초 1/2 203-자료구조(참고): 후위 표기식2

후위 표기식2(python 1935)

변수의 개수를 미리 받는 이유는 변수의 값을 따로 저장해놓을 리스트를 먼저 선언하기 위함이다
또한 후위 연산은 stack의 pop을 활용하여 계산한다
소수점 2자리까지 표현하는건 %.2f 함수를 활용한다

N = int(input())
s = str(input())
num = [0] * N
post_stack = []

for i in range(N):
    num[i] = int(input())

for i in s:
    if i.isalnum():
        post_stack.append(num[ord(i) - ord('A')])
    else:
        n2 = post_stack.pop()
        n1 = post_stack.pop()

        if i == '+':
            post_stack.append(n1 + n2)

        elif i == '-':
            post_stack.append(n1 - n2)

        elif i == '*':
            post_stack.append(n1 * n2)

        elif i == '/':
            post_stack.append(n1 / n2)

print('%.2f' %post_stack[0])