1224. [S/W 문제해결 기본] 6일차 - 계산기3

dannyp0930·2021년 8월 26일
0

SW Expert Academy

목록 보기
10/14
post-thumbnail

출처 : 링크텍스트

1. 풀이 방법

문제 계산기2에 괄호를 포함하여 푸는 문제이다. icp와 isp를 딕셔너리로 생성하여 우선순위를 적용하여 풀이하였다.

2. 코드

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()))))
profile
Newbie 개발자

0개의 댓글