Algorithm/programmers/2020 카카오 인턴십/level2/ 수식 최대화(with python)

yellow·2021년 6월 19일
0

알고리즘 문제

목록 보기
47/58

📖 문제

📝 풀이 과정

  1. 주어진 연산식 expression에서 연산자와 피연산자들을 각각 다른 리스트에 담는다.
  2. python의 permutations모듈을 사용하여 연산자 *, +, -의 순열을 모두 구한다.
    -> 우선순위를 결정(좌측에 있을수록 우선순위가 높다)
  3. 2번에서 구한 모든 우선순위에 대해 연산식 expression을 계산하는 함수calculation을 호출한다. 그리고 그 리턴값을 리스트 result에 저장
  4. 리스트 result에 있는 요소들 중 최댓값이 정답

⌨ 코드

from itertools import permutations as p
import re

# priority라는 우선순위에 따라 expression을 계산한 결과를 리턴하는 함수
def calculation(operators, operands, priority):
    priority = list(priority)
    # operators와 operands의 원본 리스트의 손상을 방지하기 위해 다른 리스트에 담아서 사용
    operat = operators[:]
    operan = operands[:]
    for cur_op in priority:
        while True:     
            if cur_op in operat:
                # 현재 연산자의 위치(인덱스)를 찾는다.
                op_idx = operat.index(cur_op)
            else:
                break

            if cur_op == '*':
                operan[op_idx] = operan[op_idx] * operan[op_idx+1]
            elif cur_op == '+':
                operan[op_idx] = operan[op_idx] + operan[op_idx+1]
            elif cur_op == '-':
                operan[op_idx] = operan[op_idx] - operan[op_idx+1]
                
            # 계산 후 필요없는 요소들 제거
            operan.pop(op_idx+1)
            operat.pop(op_idx)
    return operan[0] if operan[0] > 0 else -operan[0]
    
def solution(expression):
    # '+', '-', '*'의 우선순위로 가능한 모든 경우에 대한 연산 결과를 담는 리스트
    result = []
    operand = ['+', '-', '*']

    # 피연산자를 담는 리스트
    operands = list(map(int,re.split('[*+-]', expression)))
    # 연산자를 담는 리스트
    operators = list(re.split('[0-9]+', expression))[1:-1]

    #  p(operand,3) : '+','-','*'의 우선순위로 가능한 모든 경우를 담은 리스트
    for priority in p(operand,3):
        result.append(calculation(operators, operands, priority))

    return max(result)
profile
할 수 있어! :)

0개의 댓글