1935. 후위 표기식2

sen·2021년 7월 23일
0

BOJ

목록 보기
9/38
post-thumbnail

문제

백준 1935번 후위 표기식2


풀이

각 알파벳에 대응되는 값을 넣어주기 위해 딕셔너리를 사용했다.
표기식을 숫자로 바꿔주고 난 다음은 스택으로 계산하면 된다.

출력형식이 소수 둘째자리까지인데 까먹어서 검색해서 풀었다.

n = int(input())
post = list(input())
num = dict()
for i in range(65, 65+n):
    num[chr(i)] = int(input())
for i in range(len(post)):
    if post[i].isalpha(): post[i] = num[post[i]]

st = []
while post:
    x = post.pop(0)
    if x in ['+', '-', '*', '/']: 
        if st:
            b, a = st.pop(), st.pop()
            if x == '+': st.append(a + b)
            elif x == '-': st.append(a - b)
            elif x == '*': st.append(a * b)
            else: st.append(a / b)
    else:
        st.append(float(x))
print('%.2f'%st.pop())
profile
공부 아카이브

0개의 댓글