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

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

programmers.co.kr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def solution(expression):
    expression = re.split('([-/+/*])', expression)  # () 로 묶음
    ans = []
    for operator in permutations(['+''-''*'], 3):
        temp = expression[:]
        for op in operator:
            while op in temp:  # ['50', '*', '6', '-', '3', '*', '2']
                index = temp.index(op)
                temp[index - 1= str(eval(temp[index - 1+ op + temp[index + 1]))
                del temp[index:index + 2]  # ['300', '-', '3', '*', '2']
        # 연산자 계산 완료 = [42000] 하나의 값만 남음
        ans.append(abs(int(temp[0])))
    return max(ans)
 
 
expression = "100-200*300-500+20"
print(solution(expression))
cs

1. 
ex) * 계산

    1. ['50', '*', '6', '-', '3', '*', '2']
    2. ['300', '-', '3', '*', '2']
첫 번째 '*'의 index = 1,
temp[index - 1] = 50
temp[index + 1] = 6
eval을 통해 나온 값을 temp[index -1] = 300 대입하고, index 와 index + 1 항을 슬라이싱으로 del 해준다.

복잡한 계산 없이 index를 단순하게 합치고 삭제하면 된다.
eval은 int를 반환하므로 다시 str로 형변환 해줄 것

 

2.
expression = "50*6-3*2"
nums = re.split('[+/*/-]', expression)  # ['50', '6', '3', '2']

nums2 = re.split('([-/+/*])', expression)  # ['50', '*', '6', '-', '3', '*', '2'], -는 가운데에 놓으면 인식이 안된다.

결론: ( )로 묶어주면 [ ]의 문자들을 기준으로 나눈 다음, [ ]의 문자들도 그대로 남겨놓는다.

 

+ Recent posts