알고리즘/프로그래머스

[프로그래머스 | Lv2] 수식 최대화 (Python) - 2020 카카오 인턴십

sssbin 2023. 3. 6. 14:34

 

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

 

프로그래머스

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

programmers.co.kr

 

숫자(num), 연산자(op)를 분리해주고 연산자 우선순위 리스트(per)를 순열을 통해 만들어준다.

per을 순서대로 돌면서 각 연산자에 대해 계산을 해주고,

(연산자의 개수는 항상 숫자의 개수보다 하나 적음, 연산자의 idx -> 숫자[idx]와 숫자[idx+1]의 연산을 수행하면 됨)

각 우선순위에 따라 절댓값의 최댓값을 갱신해주면 된다.

 

# 프로그래머스 67257: 수식 최대화 (2020 카카오 인턴십)

import re
from itertools import permutations

def solution(expression):
    num = list(map(int, re.split('\+|\-|\*', expression))) # 숫자
    op = re.split('[0-9]+', expression)[1:-1] # 연산자
    per = list(permutations(set(op), len(set(op)))) # 연산자 우선순위

    answer = 0
    for p in per:
        n = num[:]
        o = op[:]

        i = 0
        while i < len(p):
            while p[i] in o:
                idx = o.index(p[i])
                tmp = o.pop(idx)

                if tmp == '+':
                    n[idx] += n.pop(idx+1)
                elif tmp == '-':
                    n[idx] -= n.pop(idx+1)
                else:
                    n[idx] *= n.pop(idx+1)
            
            i += 1
        
        answer = max(answer, abs(n[0]))
        
    return answer