본문 바로가기

Coding Test/Programmers

[프로그래머스/파이썬] 수식 최대화

728x90

 

나의 풀이

def solution(expression):
    ranks = [
        ['+', '-', '*'],
        ['+', '*', '-'],
        ['-', '+', '*'],
        ['-', '*', '+'],
        ['*', '+', '-'],
        ['*', '-', '+']
    ]
    result, operator, operand = [], [], []

    for i, n in enumerate(expression):
        if n in ranks[0]:
            operator.append(n)
        elif i == 0 or (expression[i - 1]) in ranks[0]:
            operand.append(int(n))
        else:
            operand[-1] = operand[-1] * 10 + int(n)

    for rank in ranks:
        temp_operator = list(operator)
        temp_operand = list(operand)
        for i in range(3):
            idx = 0
            while temp_operator and idx < len(temp_operator):
                if temp_operator[idx] == rank[i] == '+':
                    temp_operator.pop(idx)
                    temp_operand[idx] += temp_operand.pop(idx + 1)
                elif temp_operator[idx] == rank[i] == '-':
                    temp_operator.pop(idx)
                    temp_operand[idx] -= temp_operand.pop(idx + 1)
                elif temp_operator[idx] == rank[i] == '*':
                    temp_operator.pop(idx)
                    temp_operand[idx] *= temp_operand.pop(idx + 1)
                else:
                    idx += 1
        result.append(abs(temp_operand[0]))

    return max(result)

 

 

eval을 사용한 풀이

def solution(expression):
    operations = [('+', '-', '*'),('+', '*', '-'),('-', '+', '*'),('-', '*', '+'),('*', '+', '-'),('*', '-', '+')]
    answer = []
    for op in operations:
        a = op[0]
        b = op[1]
        temp_list = []
        for e in expression.split(a):
            temp = [f"({i})" for i in e.split(b)]
            temp_list.append(f'({b.join(temp)})')
        answer.append(abs(eval(a.join(temp_list))))
    return max(answer)
반응형