728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
백트래킹을 풀어보려 했으나, 잘 풀리지 않아서 풀지 못했다.
계속 Index out of range 오류가 나서 잡는데 시간이 너무 오래걸림 ㅠㅠ
풀이
from itertools import permutations
import re
def solution(expression):
answer = 0
expression = re.split('([*+-])', expression) # *, +, - 로 나눈 리스트
operators = list(permutations(['+', '-', '*']))
for operator in operators: # ('*', '+', '-')
temp_exp = expression.copy()
for op in operator:
while op in temp_exp:
index = temp_exp.index(op)
temp_exp[index - 1] = str(eval(temp_exp[index - 1] + temp_exp[index] + temp_exp[index + 1])) # index - 1 위치의 값을 (index-1) (op) (index+1)을 계산한 값으로 변경
del temp_exp[index:index+2] # index, index+1 위치에 있는 값 제거
answer = max(answer, abs(int(temp_exp[0])))
return answer
참고 링크
[프로그래머스, Python] 수식 최대화
프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요. programmers.co.kr 먼저, per
toki0411.tistory.com
728x90