코딩테스트/프로그래머스

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

박소민 2025. 5. 22. 12:02
수식 최대화
 

프로그래머스

SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

  • 내 풀이
    • 입력 식을 숫자와 연산자 단위로 분리 → 리스트(exp)에 저장
    • 식에 등장하는 연산자 종류(flag)를 집합으로 수집
    • 연산자 우선순위 모든 순열(permutations)을 생성
    • 각 우선순위별로 연산을 반복 수행하며 식 간소화 → 최종값 도출
      • eval() : 문자열로된 계산식을 계산해서 int 값으로 반환
    • 최종값 절댓값 중 최대값을 답으로 반환
from itertools import permutations

def solution(expression):
    answer = 0
    n=len(expression)
    
    exp=[]
    flag=set()
    num=""
    for i, ep in enumerate(expression):
        if i==n-1:
            num+=ep
            exp.append(num)
        elif ep.isdigit():
            num+=ep
            continue
        else:
            flag.add(ep)
            exp.append(num)
            exp.append(ep)
            num=""
    
    for perm in permutations(flag,len(flag)):
        tmp=exp[:]
        
        for p in perm:
            while p in tmp:
                idx=tmp.index(p)
                tmp[idx-1]=str(eval(''.join(tmp[idx-1:idx+2])))
                del tmp[idx:idx+2]
        
        answer=max(answer,abs(int(tmp[0])))
            
    return answer