[프로그래머스] 수식 최대화

HL·2021년 2월 22일
0

프로그래머스

목록 보기
16/44

문제 링크

https://programmers.co.kr/learn/courses/30/lessons/67257

문제 설명

  • 연산자 +, -, * 의 우선순위를 정한다
  • 결과값의 절대값의 최댓값 리턴

풀이

  • permutation을 사용해 연산자 우선순위의 경우의 수를 구한다
  • 각 순서마다 우선순위 역순으로 split
  • 이후 순서대로 값 계산

느낀 점

  • 다른 사람들의 풀이를 보니 eval 함수를 사용하더라
  • 매우 편리한 함수인 것 같다
  • 실제 개발에서는 사용을 비추한다고 한다

코드

from itertools import permutations


def solution(expression):
    answer = 0
    for p in permutations(['+', '-', '*'], 3):
        answer = max(answer, abs(get_money(expression, p)))
    return answer


def get_money(expression, p):
    o1, o2, o3 = p
    result = expression.split(o3)
    for i in range(len(result)):
        result[i] = result[i].split(o2)
        for j in range(len(result[i])):
            result[i][j] = result[i][j].split(o1)
            result[i][j] = get_num(result[i][j], o1)
        result[i] = get_num(result[i], o2)
    result = get_num(result, o3)
    return result


def get_num(numbers, operation):
    if operation == '+':
        return sum(map(int, numbers))
    elif operation == '-':
        result = int(numbers[0])
        for i in range(1, len(numbers)):
            result -= int(numbers[i])
        return result
    elif operation == '*':
        result = 1
        for n in numbers:
            result *= int(n)
        return result
profile
Swift, iOS 앱 개발을 공부하고 있습니다

0개의 댓글