출처 : 링크텍스트
중위표기식으로 표현된 수식을 후위표기식으로 변경하여 계산하는 문제이다. stack
을 활용하는 기본적인 문제이다.
def postfix(a):
stack = []
temp = []
for e in a:
if e == '+':
while stack:
temp.append(stack.pop())
stack.append(e)
elif e == '*':
stack.append(e)
else:
temp.append(e)
while stack:
temp.append(stack.pop())
return temp
def calculate(a):
stack = []
for e in a:
if e == '+':
stack.append(stack.pop() + stack.pop())
elif e == '*':
stack.append(stack.pop() * stack.pop())
else:
stack.append(int(e))
return stack[0]
for tc in range(1, 11):
n = int(input())
print('#{0} {1}'.format(tc, calculate(postfix(input()))))