문제
https://programmers.co.kr/learn/courses/30/lessons/67257
코딩테스트 연습 - 수식 최대화
IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과
programmers.co.kr
풀이
어느 카테고리에 속하는 문제인지 고민하다 완전탐색으로 풀기로 했다.
그런데 연산을 하는 과정 자체가 좀 까다로웠다.
먼저 연산자랑 피연산자를 나누는 방법에 대해 고민하다 반복문밖에 떠오르지 않아 다른 사람의 풀이를 봤다
정규식에서 split 메소드를 제공하는 것을 알게 되었다. (https://docs.python.org/ko/3/library/re.htmlhttps://docs.python.org/ko/3/library/re.html)
import re
re.split('[+*-]', exp)
주의* -이 중간에 들어가면 ~부터 ~까지라는 뜻이 됨
deep copy 방법도 복습
import copy
b = copy.deepcopy(a)
operand와 operator를 나누지 않고 하나의 리스트에 담는 방법이다.
\D는 digit이 아닌 것을 뜻한다.
eval("300 + 400") #식을 문자열로 받아 계산해주는 함수
# 700
그렇게 완성한 코드..
from itertools import permutations
import copy
import re
def solution(expression):
answer = 0
perm = list(permutations(['+', '-', '*'], 3))
for pe in perm:
exp = copy.deepcopy(expression)
ex = re.split('(\D)', exp)
for p in pe:
while p in ex:
idx = ex.index(p)
ex[idx-1] = eval(str(ex[idx-1]) + ex[idx] + str(ex[idx+1]))
del ex[idx]
del ex[idx]
answer = max(answer, abs(int(ex[0])))
return answer
모르는 문법들이 많아 거의 베끼다싶이 본 것 같다 ㅠ
다른 사람의 풀이
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)
'알고리즘 스터디 2021.07~' 카테고리의 다른 글
[프로그래머스] 2020 카카오 인턴십 - 키패드 누르기 (0) | 2021.08.10 |
---|---|
[프로그래머스] 2018 카카오 블라인드 [1차] 뉴스 클러스터링 (0) | 2021.08.08 |
[프로그래머스] 2018 카카오 블라인드 - [1차] 추석 트래픽 (0) | 2021.07.16 |
[프로그래머스] 2019 카카오 겨울인턴 - 크레인 인형뽑기 (2) | 2021.07.16 |
[프로그래머스] 2020 카카오 문자열 압축 (0) | 2021.07.11 |