알고리즘

수식 최대화

완달프 2021. 5. 8. 02:49

문제

수식이 주어졌을때 연산자 우선순위를 바꿔서 얻을 수 있는 값의 최대 절대값을 얻어야 한다.

 

풀이방법

일단 배열로 식을 분리하고, 모든 경우의 수로 식을 계산해본다.

최대값만 저장해서 최후에 반환한다.

 

programmers.co.kr/learn/courses/30/lessons/67257

 

from itertools import permutations


def solution(expression):
    nexpression = []
    operand = ""
    # 식을 배열로 구분하기
    for index, char in enumerate(expression):
        if char in "0123456789":
            operand += char
        elif char in "+-*":
            nexpression.append(operand)
            nexpression.append(char)
            operand = ""
        if index == len(expression) - 1:
            nexpression.append(operand)
    # 모든 경우의수에서 최대값 구하기
    MAX = 0
    for priority in permutations("+-*"):
        nnexpression = nexpression[:]
        for operation in priority:
            while operation in nnexpression:
                operation_index = nnexpression.index(operation)
                result = eval("".join(nnexpression[operation_index-1:operation_index+2]))
                nnexpression = nnexpression[:operation_index-1] + [str(result)] + nnexpression[operation_index+2:]
        MAX = max(MAX, abs(int(nnexpression[0])))
    answer = MAX
    return answer

print(solution("100-200*300-500+20") == 60420)
print(solution("50*6-3*2") == 300)

'알고리즘' 카테고리의 다른 글

튜플  (0) 2021.05.08
보석 쇼핑  (0) 2021.05.08
동굴 탐험  (0) 2021.05.06