2023-04-30 수식 최대화

시도한 방법

  1. 일단 숫자와 연산자를 분리하여 리스트에 담는다.
  2. 순열을 통해 구한 연산자 우선순위 (최대 6가지) 에 대하여 연산에 대한 수식을 계산한다. (비효율적인 방법이지만 입력 크기가 제한적이므로 충분히 가능한 방법)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from itertools import permutations

def solution(expression):

   def calc(substr):
      if substr[1] == '*':
         return int(substr[0]) * int(substr[2])
      elif substr[1] == '+':
         return int(substr[0]) + int(substr[2])
      elif substr[1] == '-':
         return int(substr[0]) - int(substr[2])

   start = -1
   lst = []
   op = ['*', '+', '-']
   for i in range(len(expression)):
      if expression[i].isnumeric():
         if start == -1:
            start = i
      else:
         lst.append(expression[start:i])
         lst.append(expression[i])
         start = -1
   lst.append(expression[start:i+1])

   ans = 0
   for perm in permutations(op):
      tmp = lst[::]
      for op in perm:
         while op in tmp:
            idx = tmp.index(op)
            tmp[idx-1] = str(calc(tmp[idx-1:idx+2]))
            tmp[idx] = tmp[idx+1] = ''
            tmp = [i for i in tmp if i]
      ans = max(ans, abs(int(tmp[0])))
   return ans

comments powered by Disqus