728x90
나의 풀이
def solution(expression):
ranks = [
['+', '-', '*'],
['+', '*', '-'],
['-', '+', '*'],
['-', '*', '+'],
['*', '+', '-'],
['*', '-', '+']
]
result, operator, operand = [], [], []
for i, n in enumerate(expression):
if n in ranks[0]:
operator.append(n)
elif i == 0 or (expression[i - 1]) in ranks[0]:
operand.append(int(n))
else:
operand[-1] = operand[-1] * 10 + int(n)
for rank in ranks:
temp_operator = list(operator)
temp_operand = list(operand)
for i in range(3):
idx = 0
while temp_operator and idx < len(temp_operator):
if temp_operator[idx] == rank[i] == '+':
temp_operator.pop(idx)
temp_operand[idx] += temp_operand.pop(idx + 1)
elif temp_operator[idx] == rank[i] == '-':
temp_operator.pop(idx)
temp_operand[idx] -= temp_operand.pop(idx + 1)
elif temp_operator[idx] == rank[i] == '*':
temp_operator.pop(idx)
temp_operand[idx] *= temp_operand.pop(idx + 1)
else:
idx += 1
result.append(abs(temp_operand[0]))
return max(result)
eval을 사용한 풀이
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)
반응형
'Coding Test > Programmers' 카테고리의 다른 글
[프로그래머스/파이썬] 빛의 경로 사이클 (0) | 2022.06.13 |
---|---|
[프로그래머스/파이썬] 튜플 (0) | 2022.06.13 |
[프로그래머스/파이썬] 거리두기 확인하기 (0) | 2022.06.12 |
[프로그래머스/파이썬] [1차] 뉴스 클러스터링 (0) | 2022.06.12 |
[프로그래머스/파이썬] 괄호 변환 (0) | 2022.06.11 |