[프로그래머스] Level2, 수식최대화 (Python)

2021. 9. 10. 11:36·알고리즘/프로그래머스
728x90
반응형

문제

https://programmers.co.kr/learn/courses/30/lessons/67257?language=python3 

 

코딩테스트 연습 - 수식 최대화

IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과

programmers.co.kr

 

코드

from itertools import permutations
def solution(expression):
    answer = []
    exp = []
    op = ['-', '+', '*']
    demo = ''
    per = list(permutations(op, 3))
    for i in expression:
        if i.isdigit():
            demo += i
        else:
            exp.append(demo)
            exp.append(i)
            demo = ''
    exp.append(demo)
    
    print(exp)
    for i1, i2, i3 in per:
        temp = []
        for j in range(len(exp)):
            if temp:
                if temp[-1] == i1:
                    temp.pop()
                    if i1 == '-':
                        temp[-1] = int(temp[-1]) - int(exp[j])
                    elif i1 == '+':
                        temp[-1] = int(temp[-1]) + int(exp[j])
                    else:
                        temp[-1] = int(temp[-1]) * int(exp[j])
                else:
                    temp.append(exp[j])
            else:
                temp.append(exp[j])
        temp2 = []
        for k in range(len(temp)):
            if temp2:
                if temp2[-1] == i2:
                    temp2.pop()
                    if i2 == '-':
                        temp2[-1] = int(temp2[-1]) - int(temp[k])
                    elif i2 == '+':
                        temp2[-1] = int(temp2[-1]) + int(temp[k])
                    else:
                        temp2[-1] = int(temp2[-1]) * int(temp[k])
                else:
                    temp2.append(temp[k])
            else:
                temp2.append(temp[k])
        temp3 = []
        for m in range(len(temp2)):
            if temp3:
                if temp3[-1] == i3:
                    temp3.pop()
                    if i3 == '-':
                        temp3[-1] = int(temp3[-1]) - int(temp2[m])
                    elif i3 == '+':
                        temp3[-1] = int(temp3[-1]) + int(temp2[m])
                    else:
                        temp3[-1] = int(temp3[-1]) * int(temp2[m])
                else:
                    temp3.append(temp2[m])
            else:
                temp3.append(temp2[m])

        answer.append(abs(temp3[0]))
                    
    return max(answer)

 

isdigit() 함수를 사용해서 연산자와 피연산자를 나눠서 리스트에 저장해준다.

그리고 연산자가 최대 3개이기 때문에 permutations로 모든 경우의 수를 확인해 연산해준다.

 

새로운 리스트를 한개 만들어 연산자와 피연산자가 들어있는 리스트를 한개씩 새로운 리스트에 넣어주고

 

현재 우선순위 연산자가 새로운 리스트 맨 마지막에 들어있다면

 

pop()을 해서 연산자를 제거해준다음 새로운 리스트 맨마지막에 연산한 값을 넣어준다.

 

이 과정을 반복해서 절대값이 가장 큰 값을 구하면 된다.

반응형
저작자표시 (새창열림)

'알고리즘 > 프로그래머스' 카테고리의 다른 글

[프로그래머스] Level2, 배달 (Python)  (0) 2021.09.13
[프로그래머스] Level3, 불량 사용자 (Python)  (0) 2021.09.10
[프로그래머스] Level2, 거리두기 확인하기 (Python)  (0) 2021.08.25
[프로그래머스] Level3, 자물쇠와 열쇠 (Python)  (0) 2021.08.10
[프로그래머스] Level3, 합승 택시 요금 (Python)  (0) 2021.08.10
'알고리즘/프로그래머스' 카테고리의 다른 글
  • [프로그래머스] Level2, 배달 (Python)
  • [프로그래머스] Level3, 불량 사용자 (Python)
  • [프로그래머스] Level2, 거리두기 확인하기 (Python)
  • [프로그래머스] Level3, 자물쇠와 열쇠 (Python)
wookcode
wookcode
공부한 내용들을 정리하고 기록하는 블로그입니다.
    반응형
  • wookcode
    wookcode
    wookcode
  • 전체
    오늘
    어제
    • 카테고리 (196) N
      • study (1) N
        • 아파치 카프카 애플리케이션 프로그래밍 with 자.. (0)
        • 인프런 (1) N
      • Live Study (15)
      • Programming (14)
        • Java (8)
        • Python (1)
        • Springboot (5)
        • MSA (0)
      • 알고리즘 (117)
        • 백준 (58)
        • 프로그래머스 (59)
      • 에러로그 (5)
      • 항해99 (23)
      • 면접 (1)
      • 프로젝트 (1)
      • CS (19)
        • 네트워크 (2)
        • 운영체제 (2)
        • 데이터베이스 (2)
        • 컴퓨터구조 (1)
        • Java (8)
        • Spring (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    회고
    그리디
    코딩테스트
    파이썬
    spring
    java
    정리
    카카오인턴
    괄호
    항해99
    orm
    SpringBoot
    프로그래머스
    실전프로젝트
    조합
    항해마켓
    에러
    브루트포스
    김영한
    인프런
    백준
    스파르타코딩클럽
    알고리즘
    카카오코딩테스트
    미니프로젝트
    해결
    버그
    jpa
    후기
    SFlash
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
wookcode
[프로그래머스] Level2, 수식최대화 (Python)
상단으로

티스토리툴바