수식 최대화 - python(programmers)

참치돌고래·2021년 8월 30일
0

알고리즘

목록 보기
19/36
post-custom-banner

https://programmers.co.kr/learn/courses/30/lessons/67257

from itertools import permutations
import copy

def solution(expression):
    
    answer = []
    digit = []
    operators= []
    tmp = ''
    for e in expression:
        
        if e.isdigit():
            tmp +=e
            
        elif e.isdigit() == False:
            digit.append(int(tmp))
            operators.append(e)
            digit.append(e)
            tmp = '' 
    digit.append(int(tmp))
    
    operators= list(set(operators))
    
    operators = list(permutations(operators, len(operators)))
    
    
    for priority in operators:
        #print(priority)
        tmp_list = copy.deepcopy(digit)
        for i in priority:
            tmp = 0
            idx=1
            #print("operator",i)
            while (idx < len(tmp_list)-1):
                if tmp_list[idx] == i:
                    #print(tmp_list[idx-1], tmp_list[idx], tmp_list[idx+1])
                    tmp=calculate(tmp_list[idx-1], tmp_list[idx+1], tmp_list[idx])
                    del tmp_list[idx-1]
                    del tmp_list[idx-1]
                    del tmp_list[idx-1]
                    tmp_list.insert(idx-1,tmp)
                    idx-=1
                idx+=1
        #print(tmp_list)
        answer.append(abs(tmp_list[0]))
        
    return max(answer)


def calculate(x,y,s):
    if s == '+':
        return x+y
    elif s == '-':
        return x-y
    elif s == '/':
        return x/y
    elif s == '*':
        return x*y
profile
안녕하세요
post-custom-banner

0개의 댓글