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

 

코딩테스트 연습 - 수식 최대화

IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과 �

programmers.co.kr



Solution

import itertools

def operation(num1, num2, op):
    if op == '+':
        return str(int(num1) + int(num2))
    if op == '-':
        return str(int(num1) - int(num2))
    if op == '*':
        return str(int(num1) * int(num2))

def calculate(expression, op):
    cal_tmp = []
    print(op)
    for i in expression:
        if not i in op:
            if len(cal_tmp) != 0 and not cal_tmp[-1] in op:
                cal_tmp[-1] = cal_tmp[-1] + i
            else:
                cal_tmp.append(i)
        else:
            cal_tmp.append(i)
    
    result = []
    stack = []
    for o in op:
        while True:
            if len(cal_tmp) == 0:
                break
            tmp = cal_tmp.pop(0)
            if tmp == o:
                stack.append(operation(stack.pop(-1), cal_tmp.pop(0), o))
            else:
                stack.append(tmp)
        result.append(stack)
        cal_tmp = stack
        stack = []
            
    return result[-1]

def solution(expression):
    op = ['+', '-', '*']
    op = list(itertools.permutations(op, 3))
    answer = 0
    for i in op:
        answer = max(answer, abs(int(calculate(expression, i)[0])))
    return answer

 

연산자가 '+', '-', '*' 세 개밖에 되지 않아 될 수 있는 모든 경우의 수를 구하고 경우의 수를 하나씩 검사해서 제일 큰 값을 리턴한다. 먼저 calculate함수에서 expression을 숫자와 연산자를 구분해서 나눈다. 그리고 stack을 하나 만들어 stack에 하나씩 값을 넣는데, 연산자의 순서에 따라 우선순위가 높은 연산자에 해당 되는 연산자면 stack에 가장 마지막에 들어간 수와 cal_tmp에 들어있는 그 다음 수를 해당 연산자에 맞게 연산한다. 그리고 연산한 stackresult에 담는다. 연산자 세 개를 다 확인할 경우 stack에 수 하나만 남게되고, 그 수를 리턴한다. 다른 분들은 어떨지 모르겠지만, LEVEL2 치고 생각보다 까다로웠다😩


생강강

,