티스토리 뷰
후위표기식은 계산하기 매우 쉽다.
식을 앞에서부터 읽으면서 수가 나오면 push, 기호가 나오면 스택의 가장 위에있는 두 수를 pop해서 계산
소스코드
import string
AtoZ = string.ascii_uppercase
dict1 = {}
n = int(input())
st = input()
stack = []
for i in range(n):
dict1.update({AtoZ[i]:int(input())})
for i in range(len(st)):
if st[i].isalpha():
stack.append(dict1[st[i]])
else:
b = stack.pop()
a = stack.pop()
if st[i] == '+':
stack.append(a+b)
elif st[i] == '-':
stack.append(a-b)
elif st[i] == '*':
stack.append(a*b)
else:
stack.append(a/b)
print("{:.2f}".format(stack[0]))