from itertools import permutations
def solution(expression):
answer = 0
expressionList = list(expression.replace('+', ' + ')
.replace('-', ' - ')
.replace('*', ' * ')
.split(' '))
operation = [ch for ch in expression if not ch.isdigit()] # 연산자만 분리한 리스트
precedences = list(permutations(set(operation))) # 연산자 우선순위 순열
for precedence in precedences:
tmpList = expressionList
for pre in precedence:
stack = []
for num2 in tmpList:
if stack and stack[-1] == pre:
stack.pop()
num1 = stack.pop()
stack.append(str(eval(num1 + pre + num2)))
else:
stack.append(num2)
tmpList = stack
answer = max(answer, abs(int(tmpList[0])))
return answer
예를 들어 우선순위가
* > - > +
일때,*
부터 계산한다. 스택에 원소를 하나씩 넣다가 스택의 최상단 값이*
이면 두번 꺼내서 계산한 후 결과값을 넣는다.
이때 처음 꺼내지는건 연산자이고 두번째로 꺼내지는건 숫자num1
이다.
*
연산 후 남은 수식들이tmpList
에 들어간다.*
연산이 끝난후 다음으로 우선순위가 높은-와 +
를 계산한다.
tmpList
에는 최종 결과값만 남는다. 최종 결과값의 절대값과 answer
중 더 큰값을 answer
에 넣는다.쉽지 않았ㄷr..