[PS] 수식 최대화

owo·2023년 1월 28일
0

PS

목록 보기
7/25

문제 링크

코드

def solution(expression):
    ops = {"+", "-", "*"}
    orders = [
        ["+", "-", "*"], 
        ["+", "*", "-"], 
        ["-", "+", "*"], 
        ["-", "*", "+"], 
        ["*", "+", "-"], 
        ["*", "-", "+"]
    ]
    
    numbers = []
    operators = []
    before = 0
    for cur in range(len(expression)):
        if expression[cur] in ops:
            numbers.append(int(expression[before:cur]))
            operators.append(expression[cur])
            before = cur + 1
    numbers.append(int(expression[before:]))
    
    answer = 0
    for order in orders:
        nums = numbers[:]
        ops = operators[:]
        while order:
            op = order.pop()
            while op in ops:
                idx = ops.index(op)
                ops.pop(idx)
                n1 = nums.pop(idx)
                n2 = nums.pop(idx)
                
                if op == "+":
                    nums.insert(idx, n1 + n2)
                elif op == "-":
                    nums.insert(idx, n1 - n2)
                else:
                    nums.insert(idx, n1 * n2)
        
        answer = max(answer, abs(nums[0]))
    
    return answer
    

리뷰

  • 연산자 우선순위의 종류가 6개밖에 안되기 때문에 단순 구현 문제라고 생각했다. 처음 생각했던 것처럼 숫자와 연산자들을 나누고, 우선순위가 높은 연산자부터 계산하는 방식으로 풀었다.
  • 중간에 deepcopy 관련 문제가 발생했다. collections을 복사할 때에는 항상 신경써야겠다.
  • 다른 사람들의 풀이를 보니 문자열을 split하고 join하면서 간결하게 구현한 코드를 찾을 수 있었다. 문자열을 처리하는 방법 중 하나로 자주 사용되는 것 같다.
  • eval() 이라는 함수는 수식이 적혀있는 문자열을 실행시키는 함수이다. 하지만 검색해본 결과 큰 보안문제가 있기 때문에 코딩테스트에서만 사용하고 프로덕트 코드에서는 사용하면 안된다. 링크

0개의 댓글