출처 : 링크텍스트
문제 계산기2에 괄호를 포함하여 푸는 문제이다. icp와 isp를 딕셔너리로 생성하여 우선순위를 적용하여 풀이하였다.
icp = {'(': 3, '*': 2, '+': 1, ')': 0}
isp = {'(': 0, '*': 2, '+': 1}
def postfix(a):
stack = []
temp = []
for e in a:
if e in icp.keys():
if not stack:
stack.append(e)
elif e == ')':
while stack[-1] != '(':
temp.append(stack.pop())
stack.pop()
else:
while icp[e] <= isp[stack[-1]]:
temp.append(stack.pop())
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()))))