[PG] 수식 최대화 계산

nerry·2022년 5월 6일
0

알고리즘

목록 보기
83/86

문제

me

python

import itertools
def solution(expression):
    temp=''
    operands,operators=[],[]
    for e in expression:
        if e.isnumeric() :
            temp+=e
        else:
            operands.append(int(temp))
            temp=''
            operators.append(e)
    operands.append(int(temp))
    sums=[]
    for rators  in itertools.permutations(['+', '-', '*']):
        t_rators=operators[:]
        t_rands=operands[:]
        for r in rators:
            while r in t_rators:
                o = t_rators.index(r)
                if t_rators[o] == '+':
                    sum = (t_rands[o]+t_rands[o+1])
                elif t_rators[o] == '-':
                    sum = (t_rands[o] - t_rands[o + 1])
                elif t_rators[o] == '*':
                    sum = (t_rands[o]*t_rands[o+1])
                t_rands[o]=sum
                del t_rands[o+1]
                del t_rators[o]
        sums.append(abs(t_rands[0]))
    return max(sums)

JavaScript

function solution(expression) {
  let answer=0
  const cases = [
    ['*', '+', '-'], ['*', '-', '+'], ['+', '*', '-'],
    ['+', '-', '*'], ['-', '+', '*'], ['-', '*', '+'],
  ];
  let operators = []
  let operands = []
  temp=''
  for(let i=0;i<expression.length;i++){
    if(['+','-','*'].includes(expression[i])){
      operands.push(Number(temp))
      temp=''
      operators.push(expression[i])
    }
    else temp+=expression[i]
  }
  operands.push(Number(temp))
  cases.forEach((cands)=>{
      var temp_operators = operators.slice()
      var temp_operands = operands.slice()
      cands.forEach((cand)=>{
        while(temp_operators.includes(cand)){
          let idx = temp_operators.indexOf(cand)
          let res = 0
          if(cand==='+'){
            res = temp_operands[idx]+temp_operands[idx+1]
          } else if(cand==='-'){
            res = temp_operands[idx]-temp_operands[idx+1]
          } else if(cand==='*'){
            res = temp_operands[idx]*temp_operands[idx+1]
          }
          temp_operands[idx]=res
          temp_operands.splice(idx+1,1)
          temp_operators.splice(idx,1)
        }
      })
      answer = Math.max(answer,Math.abs(temp_operands[0]))
    })
  return answer;
}

others

python

from itertools import permutations
def calc(priority, n, expression):
    if n == 2:
        return str(eval(expression))
    if priority[n] == '*':
        res = eval('*'.join([calc(priority, n + 1, e) for e in expression.split('*')]))
    if priority[n] == '+':
        res = eval('+'.join([calc(priority, n + 1, e) for e in expression.split('+')]))
    if priority[n] == '-':
        res = eval('-'.join([calc(priority, n + 1, e) for e in expression.split('-')]))
    return str(res)


def solution(expression):
    answer = 0
    priorities = (list(permutations(['*','-','+'], 3)))
    for priority in priorities:
        res = int(calc(priority, 0, expression))
        answer = max(answer, abs(res))

    return answer
  • 모듈화가 잘된 예 같다.

import re
from itertools import permutations

def solution(expression):
    #1
    op = [x for x in ['*','+','-'] if x in expression]
    op = [list(y) for y in permutations(op)]
    ex = re.split(r'(\D)',expression)

    #2
    a = []
    for x in op:
        _ex = ex[:]
        for y in x:
            while y in _ex:
                tmp = _ex.index(y)
                _ex[tmp-1] = str(eval(_ex[tmp-1]+_ex[tmp]+_ex[tmp+1]))
                _ex = _ex[:tmp]+_ex[tmp+2:]
        a.append(_ex[-1])

    #3
    return max(abs(int(x)) for x in a)
  • 이해하는 중...

JavaScript

const solution = (expression) => {
  const numbers = expression.split(/[^0-9]/).map(v => Number(v));
  const operators = expression.split(/[0-9]/).filter(v => v);

  const formula = getFormula(numbers, operators);

  const cases = [
    ['*', '+', '-'], ['*', '-', '+'], ['+', '*', '-'],
    ['+', '-', '*'], ['-', '+', '*'], ['-', '*', '+'],
  ];

  return Math.max(...cases.map(operators => {
    let result = formula.slice();
    operators.forEach(operator => {
      result = computeByTargetOperator(result, operator);
    });

    return Math.abs(...result);
  }));
};

const getFormula = (numbers, operators) => {
  const formula = [];

  numbers.forEach((number, i) => {
    formula.push(number);

    if (operators[i]) {
      formula.push(operators[i]);
    }
  });

  return formula;
}

const computeByTargetOperator = (formula, targetOperator) => {
  const computation = {
    '+': (a, b) => a + b,
    '-': (a, b) => a - b,
    '*': (a, b) => a * b,
  }

  const stack = [];
  for (let i = 0; i < formula.length; i += 1) {
    const target = formula[i];
    if (target === targetOperator) {
      const previousValue = stack.pop();
      const nextValue = formula[i + 1];

      const result = computation[targetOperator](previousValue, nextValue);

      stack.push(result);
      i += 1;
      continue;
    }

    stack.push(target);
  }

  return stack;  
};
  • 자바스크립트를 매우 잘 활용한 것 같다
  • computation 을 객체화 시켜두고 함수를 달아둔 것이 좋아보인다.
  • split시 정규표현식을 사용한 것도 기억해야겠다.
profile
터벅터벅 개발(은좋은)자 로그

0개의 댓글