Coding Test
[프로그래머스] 수식 최대화
상상쓰
2021. 6. 8. 20:39
https://programmers.co.kr/learn/courses/30/lessons/67257
코딩테스트 연습 - 수식 최대화
IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과
programmers.co.kr
어제 배운 map, reduce 를 사용해봤다.
연산자의 우선순위를 정할 수 있는 경우의 수는 6개이다. 6개 정도면 배열로 나타냈어도 됐지만, permutations 도 한 번 써봤다.
split() 을 사용하여 우선순위가 '+' > '-' > '*' 라고 한다면,
1. '100-200*300-500+20' -> ['100-200', '300-500+20']
2-1. '100-200' -> ['100', '200'] -> -100 -> last_calculation = [-100]
2-2. '300-500+20' -> ['300', '500+20'] -> ['300', '520'] -> -220 -> last_calculation = [-100, -220]
3. -100 * -220 = 22000 -> |22000| 을 answer 과 비교
from itertools import permutations
from functools import reduce
def solution(expression):
answer = 0
operator = list(permutations(['+', '-', '*']))
for i in operator:
f, s, t = i
last_calculation = []
split_1 = expression.split(t)
for j in split_1:
split_2 = list(map(lambda x : eval(x), j.split(s)))
value = reduce(lambda x, y : eval(str(x) + s + str(y)), split_2)
last_calculation.append(value)
value = abs(reduce(lambda x, y : eval(str(x) + t + str(y)), last_calculation))
if answer < value:
answer = value
return answer
print(solution('100-200*300-500+20')) # 60420