[백준] 1918번 후위 표기식

HL·2021년 2월 27일
0

백준

목록 보기
58/104

코드

from collections import deque


def get_word():
    before = deque()
    while True:
        curr = s1.pop()
        if curr == '(':
            break
        else:
            before.appendleft(curr)
    after = deque()
    while len(before) >= 3:
        a, b, c = before.popleft(), before.popleft(), before.popleft()
        if b in {'*', '/'}:
            before.appendleft(a+c+b)
        else:
            after.append(a)
            after.append(b)
            before.appendleft(c)
    if before:
        after.append(before.pop())
    before = after
    while len(before) >= 3:
        a, b, c = before.popleft(), before.popleft(), before.popleft()
        before.appendleft(a+c+b)
    return before[0]


original = deque(input())
if original[0] != '(' or original[-1] != ')':
    original.appendleft('(')
    original.append(')')
s1 = []
for e in original:
    if e == ')':
        s1.append(get_word())
    else:
        s1.append(e)

before = deque(s1)
after = deque()
while len(before) >= 3:
    a, b, c = before.popleft(), before.popleft(), before.popleft()
    if b in {'*', '/'}:
        before.appendleft(a+c+b)
    else:
        after.append(a)
        after.append(b)
        before.appendleft(c)
if before:
    after.append(before.pop())
before = after
while len(before) >= 3:
    a, b, c = before.popleft(), before.popleft(), before.popleft()
    before.appendleft(a+c+b)
print(before[0])
profile
Frontend 개발자입니다.

0개의 댓글