[Programmers] Level 2. 수식 최대화

2022. 11. 29. 18:52·코딩테스트/Python
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

  1. 문자열은 인덱스를 통한 수정이 불가능하기 때문에, split을 통해 list화 해야 한다.
  2. 여러개의 list를 더할 때, 모두 list여야 합치는 것이 가능하다.
  3. 원본값을 수정해야 할 경우, copy해서 활용해야 이후 계산에 문제가 없다. 

'코딩테스트 > Python' 카테고리의 다른 글

[Programmers] Level 2. 행렬 테두리 회전하기  (0) 2022.12.01
[Programmers] Level 3. 가장 먼 노드  (1) 2022.12.01
[Programmers] Level 2. 방금 그 곡  (0) 2022.11.29
[Programmers] Level 3. 징검다리 건너기  (0) 2022.11.26
[Programmers] Level 3. 디스크 컨트롤러  (0) 2022.11.17
'코딩테스트/Python' 카테고리의 다른 글
  • [Programmers] Level 2. 행렬 테두리 회전하기
  • [Programmers] Level 3. 가장 먼 노드
  • [Programmers] Level 2. 방금 그 곡
  • [Programmers] Level 3. 징검다리 건너기
swwho
swwho
일상을 데이터화하다
  • swwho
    하루한장
    swwho
  • 전체
    오늘
    어제
    • 분류 전체보기 (188)
      • ML_DL (39)
        • MUJAKJUNG (무작정 시리즈) (18)
        • 딥러닝 공부하기 (21)
      • 데이터사이언스 (1)
        • EDA (1)
        • 데이터과학을 위한 통계 (0)
      • 데이터엔지니어링 (2)
      • 논문리뷰 (2)
        • Computer Vision (2)
      • Python 활용하기 (12)
      • 코딩테스트 (127)
        • Python (109)
        • MySQL (14)
      • Git (3)
      • MySQL 활용하기 (0)
      • 일상 이야기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
  • 최근 글

  • 250x250
  • hELLO· Designed By정상우.v4.10.3
swwho
[Programmers] Level 2. 수식 최대화
상단으로

티스토리툴바