[프로그래머스] 수식 최대화 (Python)

cotato·2021년 5월 7일

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

My solution

def solution(expression):
    
    operators = []
    numbers = []
    
    for c in expression:
        if not c.isdigit():
            operators.append(c)
    
    numbers = expression.replace('*', '+').replace('-', '+').split('+')
    numbers = [int(i) for i in numbers]
    
    priorities = ['+-*', '+*-', '-+*', '-*+', '*+-', '*-+']
    
    max_value = 0
    
    for priority in priorities:
        operators_copy = operators[:]
        numbers_copy = numbers[:]
        for curr_op in priority:
            i = 0
            while i < len(operators_copy):
                if curr_op == operators_copy[i]:
                    operators_copy.pop(i)
                    left = numbers_copy.pop(i)
                    right = numbers_copy.pop(i)
                    if curr_op == '+':
                        numbers_copy.insert(i, left + right)
                    elif curr_op == '-':
                        numbers_copy.insert(i, left - right)
                    elif curr_op == '*':
                        numbers_copy.insert(i, left * right)
                else:
                    i += 1

        if len(numbers_copy) != 1:
            raise Exception()
        if abs(numbers_copy[0]) > max_value:
            max_value = abs(numbers_copy[0])
    
    return max_value

eval이나 regex를 사용하면 더 간단히 풀 수도 있는 것 같은데, regex는 필요할 때 기억이 안난다...

profile
coding_potato

0개의 댓글