[백준] 1918번 후위 표기식

11070 단어 백준데크데크

코드

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])

좋은 웹페이지 즐겨찾기