https://programmers.co.kr/learn/courses/30/lessons/67257
def operation_a(l):
i = 0
while i != len(l):
try:
if l[i] == "*":
l[i] = int(l[i-1]) * int(l[i+1])
l.pop(i+1)
l.pop(i-1)
i -= 1
i += 1
except:
break
return l
def operation_b(lc):
i = 0
while i != len(lc):
try:
if lc[i] == "+":
lc[i] = int(lc[i-1]) + int(lc[i+1])
lc.pop(i+1)
lc.pop(i-1)
i -= 1
i += 1
except:
break
return lc
def operation_c(lc):
i = 0
while i != len(lc):
try:
if lc[i] == "-":
lc[i] = int(lc[i-1]) - int(lc[i+1])
lc.pop(i+1)
lc.pop(i-1)
i -= 1
i += 1
except:
break
return lc
def solution(expression):
answer = 0
expression = expression.replace("-", " - ")
expression = expression.replace("+", " + ")
expression = expression.replace("*", " * ")
l = []
l = expression.split()
answers = []
# * > + > -
lc = l.copy()
operation_a(lc)
operation_b(lc)
operation_c(lc)
answers.append(abs(int(lc[0])))
# * > - > +
lc = l.copy()
operation_a(lc)
operation_c(lc)
operation_b(lc)
answers.append(abs(int(lc[0])))
# + > * > -
lc = l.copy()
operation_b(lc)
operation_a(lc)
operation_c(lc)
answers.append(abs(int(lc[0])))
# + > - > *
lc = l.copy()
operation_b(lc)
operation_c(lc)
operation_a(lc)
answers.append(abs(int(lc[0])))
# - > + > *
lc = l.copy()
operation_c(lc)
operation_a(lc)
operation_b(lc)
answers.append(abs(int(lc[0])))
# - > * > +
lc = l.copy()
operation_c(lc)
operation_b(lc)
operation_a(lc)
answers.append(abs(int(lc[0])))
answer = max(answers)
# 절대값으로 반환하기!
return answer
그냥 간단하게 노가다로 풀었다.
1. split을 하기 위해서 + - * 앞 뒤에 공백을 넣어주었다.
2. 공백을 기준으로 split을 진행해 주었다.
3. split된 리스트를 저장해주었다.
4. 함수를 만들어 연산을 진행해준다.
5. 노가다 ( 고급지게는 브루트포스(?))로 각각의 상황에 맞게 연산을 진행해준다. 이부분은 좀 더 간단하게 만들 수도 있을 것이다.
6. 각각의 값들을 리스트에 저장해준다. 저장할 때는 문제 상황에 맞게 절대 값으로 저장해준다.
7. max()함수를 써서 최대값을 반환해주면 풀린다.