티스토리 뷰

문제 링크

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

풀이

from itertools import permutations

# 수식 숫자와 연산자로 분리
def sep_num_op(expression):
    nums, ops = [], []
    num = ""
    for s in expression:
        if s.isdigit(): # 숫자면
            num += s
        else:   # 연산자면
            nums.append(num)
            num = ""
            ops.append(s)
    nums.append(num)
    return nums, ops

# 주어진 숫자와 연산자를 사용해 우선순위에 따라 계산
def calculate(temp_nums, temp_ops, priority):
    for op in priority:
        i = 0
        while i < len(temp_ops):
            if temp_ops[i] == op:
                new_expr = temp_nums[i] + op + temp_nums[i + 1]
                temp_nums[i] = str(eval(new_expr))
                del temp_nums[i + 1]
                del temp_ops[i]
            else:
                i += 1
    return abs(int(temp_nums[0]))

# 최대값 출력
def solution(expression):
    ops = ['+', '-', '*']
    # 가능한 모든 연산자 우선순위 조합
    priorities = list(permutations(ops))
    max_result = 0

    nums, ops = sep_num_op(expression)

    for priority in priorities:
        temp_nums = nums.copy()
        temp_ops = ops.copy()

        result = calculate(temp_nums, temp_ops, priority)
        max_result = max(max_result, result)
    return max_result