[Algorithm] 수식 최대화

리쫑·2023년 2월 23일
0

Algorithm

목록 보기
14/16

수식 최대화

🤖문제 : 수식 최대화 Lv2

😎풀이

from itertools import permutations

def solution(expression) :
    answer = 0
    base_number_lst, base_math_lst = [], []
    s_i = 0
    for i, s in enumerate(expression) :
        if s in ['+', '-', '*'] :
            base_math_lst.append(s)
            base_number_lst.append(int(expression[s_i:i]))
            s_i = i+1
    base_number_lst.append(int(expression[s_i:]))
        
    for op_permu in list(permutations(list(set(base_math_lst)))) :
        number_lst = [i for i in base_number_lst]
        math_lst = [i for i in base_math_lst]
        for op_check in op_permu :
            # 각 연산자("-", "+", "*") math_lst 안에 있을 때 까지 반복
            while op_check in math_lst :
                for i_m, op in enumerate(math_lst) :
                    if op == op_check :
                        if op == '+' :
                            oper = number_lst[i_m] + number_lst[i_m+1]
                            del number_lst[i_m]
                            del number_lst[i_m]
                            number_lst.insert(i_m, oper)
                            del math_lst[i_m]
                            break
                        elif op == '*' :
                            oper = number_lst[i_m] * number_lst[i_m+1]
                            del number_lst[i_m]
                            del number_lst[i_m]
                            number_lst.insert(i_m, oper)
                            del math_lst[i_m]
                            break
                        elif op == '-' :
                            oper = number_lst[i_m] - number_lst[i_m+1]
                            del number_lst[i_m]
                            del number_lst[i_m]
                            number_lst.insert(i_m, oper)
                            del math_lst[i_m]
                            break         
        answer = abs(number_lst[0]) if abs(number_lst[0]) > answer else answer         
    
    return answer

👩‍🏫접근 방식

  • 구현 문제.
  • 동시에 여러 조건을 구현하려면 논리가 복잡해지는 경우가 많다.
  • 이럴 때 시간초과가 발생하지 않는다면, 차원분해 하듯이 조건을 여러개로 분할하여 진행하는 것이 구현 난이도나 속도 측면에서 좋다. 앞으로 "시간 체크"이후 조건을 분해하는 과정 방안을 잘 적용해봐야 겠다.
profile
AI, Data Scientist 취업 준비생 입니다. 공부한 내용을 포스팅하고자 합니다. 방문해주셔서 감사합니다

0개의 댓글