1. 개요
2. 풀이
from collections import deque
from itertools import permutations
import re
def solution(expression):
# operator와 operend 추출
tokens = re.findall("\d+|\+|\-|\*", expression)
answer = 0
# 모든 연산자 우선순위를 모두 돌려본다.
for case in permutations(("+","-","*")):
nextStack, stack = deque(), deque(t for t in tokens)
for op in case:
# 연산을 위해 stack을 활용한다.
# operator와 일치하지않으면 쌓고
# operator와 일치하면 계산한다.
while stack:
token = stack.popleft()
if token != op:
nextStack.append(token)
else:
nextStack.append(calc(nextStack.pop(), stack.popleft(), op))
nextStack, stack = stack, nextStack
answer = max(answer, abs(int(stack[0])))
return answer
def calc(left, right, op):
if op == "+":
return str(int(left)+int(right))
elif op == "-":
return str(int(left)-int(right))
else:
return str(int(left)*int(right))
Leave a comment