728x90
🔗 Problem Link
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
❔Thinking
- 주어진 +, -, * 연산자들의 우선순위를 달리하며 수식을 계산했을 때, 그 절댓값이 가장 큰 값을 반환한다.
💻Solution
from itertools import permutations
def solution(expression):
answer = []
used_expression = []
expression_list = []
# 사용된 연산자 종류 구하기
for ex in ['*', '+', '-']:
if ex in expression:
used_expression.append(ex)
# 수식 리스트화
tmp = ''
for e in expression:
if e.isdigit():
tmp += e
else:
expression_list.extend([tmp, e])
tmp = ''
expression_list.append(tmp)
# 연산자 우선순위 조합 구하기
expression_combi = permutations(used_expression, len(used_expression))
# 각 우선순위 조합 별 계산 결과 구하기
for combi in expression_combi:
temp = expression_list.copy()
for operator in combi:
while operator in temp:
idx = temp.index(operator)
temp = temp[:idx-1] + [str(eval(''.join(temp[idx-1:idx+2])))] + temp[idx+2:]
answer.append(abs(int(temp[0])))
return max(answer)
🗝️keypoint
- 문자열은 인덱스를 통한 수정이 불가능하기 때문에, split을 통해 list화 해야 한다.
- 여러개의 list를 더할 때, 모두 list여야 합치는 것이 가능하다.
- 원본값을 수정해야 할 경우, copy해서 활용해야 이후 계산에 문제가 없다.
'코딩테스트 > Python' 카테고리의 다른 글
[Programmers] Level 2. 행렬 테두리 회전하기 (0) | 2022.12.01 |
---|---|
[Programmers] Level 3. 가장 먼 노드 (0) | 2022.12.01 |
[Programmers] Level 2. 방금 그 곡 (0) | 2022.11.29 |
[Programmers] Level 3. 징검다리 건너기 (0) | 2022.11.26 |
[Programmers] Level 3. 디스크 컨트롤러 (0) | 2022.11.17 |