본문 바로가기
알고리즘/프로그래머스

[Python] 수식 최대화

by 컴공맨 2021. 3. 28.
 

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

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

programmers.co.kr


풀이

우선 정규표현식을 사용하여 숫자와 연산자를 분리하고 사용된 연산자를 구하였습니다.

다음으로 사용된 연산자에 대해 만들 수 있는 모든 우선순위의 경우들을 순열을 사용하여 만들었습니다.

그다음 만들어둔 숫자와 연산자가 담긴 리스트를 복사해서 우선순위대로 계산을 하여 절댓값을 했을 때 최대인 값을 선택하게 하여 해결했습니다.


코드

import re
from itertools import permutations


def solution(expression):
    answer = 0

    num_list = list(map(int, re.findall('\d+', expression)))
    op_list = re.findall('\D+', expression)
    op_set = set(op_list)

    op_priority_list = list(permutations(op_set, len(op_set)))

    for op_priority in op_priority_list:
        # 원본은 유지해야 모든경우에서의 최대값을 찾을 수 있다.
        calc_num_list = num_list[:]
        calc_op_list = op_list[:]

        for opp in op_priority:
            idx = 0
            while idx < len(calc_op_list):
                if opp == calc_op_list[idx]:
                    num = eval(str(calc_num_list[idx]) + calc_op_list[idx] + str(calc_num_list[idx + 1]))

                    del calc_op_list[idx]
                    del calc_num_list[idx:idx+2]

                    calc_num_list.insert(idx, num)
                    idx -= 1
                idx += 1

        if answer < abs(int(calc_num_list[0])):
            answer = abs(int(calc_num_list[0]))

    return answer

 

pyo7410/Algorithm

1일 1커밋을 목표로! Contribute to pyo7410/Algorithm development by creating an account on GitHub.

github.com

 

'알고리즘 > 프로그래머스' 카테고리의 다른 글

[Python] 프로그래머스 오픈채팅방  (0) 2021.04.11
[Python] 프로그래머스 캐시  (0) 2021.04.10
[Python] 튜플  (0) 2021.03.27
[Python] 순위 검색  (0) 2021.03.21
[Python] 괄호 변환  (0) 2021.03.21