https://programmers.co.kr/learn/courses/30/lessons/67257
나의 풀이
더보기
import itertools
import re
import copy
def solution(expression):
oper = {'+': [], '-': [], '*': []}
oper_v = {}
operator = []
operator_list = []
result = []
expression_split = re.split(r'[\+\-\*]', expression)
count = 0
for i in expression:
if i.isdigit() == False:
if i not in operator:
operator.append(i)
oper[i].append(count)
oper_v[count] = i
count += 1
for i in itertools.permutations(operator):
operator_list.append(i)
order_list = []
for i in operator_list:
tmp = []
for j in i:
tmp += oper[j]
order_list.append(tmp)
for i in order_list:
exp = copy.deepcopy(expression_split)
count = 0
idx = 0
where = copy.deepcopy(i)
while True:
if len(exp) == 1:
break
cal = exp[where[idx]] + oper_v[i[idx]] + exp[where[idx] + 1]
value = eval(cal)
exp.pop(where[idx])
exp[where[idx]] = str(value)
for l, k in enumerate(where[idx+1:]):
if k > where[idx]:
where[l+idx+1] -= 1
idx += 1
result.append(abs(int(exp[0])))
return max(result)
print(solution("100-200*300-500+20"))
print(solution("50*6-3*2"))
다른 사람의 풀이
최고의 효율인 것 같다.
더보기
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 > 프로그래머스' 카테고리의 다른 글
[Level 2] - 가장 큰 수 (0) | 2022.06.01 |
---|---|
[Level 2] - 튜플 (0) | 2022.05.14 |
[Level 2] - 1차 뉴스 클러스터링 (0) | 2022.03.06 |
[Level 2] - 괄호 변환 (0) | 2022.03.06 |
[Level 2] - 메뉴 리뉴얼 (0) | 2022.03.06 |