문제링크 : https://school.programmers.co.kr/learn/courses/30/lessons/67257
import sys
from itertools import permutations
sys.setrecursionlimit(10**6)
ans = []
def operation(num, op1, op2, op3):
# print(num)
if len(num) == 1:
ans.append(abs(int(num[0])))
return
if op1 in num:
k = num.index(op1)
if op1 == '-':
new = int(num[k - 1]) - int(num[k + 1])
elif op1 == '*':
new = int(num[k - 1]) * int(num[k + 1])
else:
new = int(num[k - 1]) + int(num[k + 1])
num.insert(k,str(new))
num.pop(k - 1)
num.pop(k)
num.pop(k)
operation(num, op1, op2, op3)
elif op2 in num:
k = num.index(op2)
if op2 == '-':
new = int(num[k - 1]) - int(num[k + 1])
elif op2 == '*':
new = int(num[k - 1]) * int(num[k + 1])
else:
new = int(num[k - 1]) + int(num[k + 1])
num.insert(k, str(new))
num.pop(k - 1)
num.pop(k)
num.pop(k)
operation(num, op1, op2, op3)
else:
k = num.index(op3)
if op3 == '-':
new = int(num[k - 1]) - int(num[k + 1])
elif op3 == '*':
new = int(num[k - 1]) * int(num[k + 1])
else:
new = int(num[k - 1]) + int(num[k + 1])
num.insert(k, str(new))
num.pop(k - 1)
num.pop(k)
num.pop(k)
operation(num, op1, op2, op3)
def solution(expression):
num = []
cnt = ''
for i in expression:
if i.isdigit():
cnt += i
else:
num.append(cnt)
cnt = ''
num.append(i)
if cnt:
num.append(cnt)
for i in permutations(['-', '*', '+'], 3):
n = num[:]
operation(n, i[0], i[1], i[2])
return(max(ans))
생각나는 방식대로 풀어봤는 데 좀 난잡하고 불필요하게 반복하는 느낌을 지울수 없었다. 다른사람들의 풀이를 봤는데 너무 기가 막힌 풀이가 있어서 그 풀이를 한번 이해하려고 노력했었다.
다른사람풀이
def solution(expression):
operations = [('+', '-', '*'),('+', '*', '-'),('-', '+', '*'),('-', '*', '+'),('*', '+', '-'),('*', '-', '+')]
answer = []
for op in operations:
a = op[0]
b = op[1]
temp_list = []
for e in expression.split(a):
temp = [f"({i})" for i in e.split(b)]
temp_list.append(f'({b.join(temp)})')
answer.append(abs(eval(a.join(temp_list))))
return max(answer)
이사람은 천재인것 같다. 연산자를 우선순위 역순으로 분해하고 ()를 통해 일반적인 사칙연산을 해도 우선순위가 바뀌도록 한다음 다시 합쳤다.
거기다가 eval이라는 함수를 알게 되었는데 쉽게 생각하면 문자열로 이루어진 숫자연산, 함수 등을 작동(?)시킨다. 좋은걸 알게 되었다.