https://school.programmers.co.kr/learn/courses/30/lessons/67257
ํ๋ก๊ทธ๋๋จธ์ค
์ฝ๋ ์ค์ฌ์ ๊ฐ๋ฐ์ ์ฑ์ฉ. ์คํ ๊ธฐ๋ฐ์ ํฌ์ง์ ๋งค์นญ. ํ๋ก๊ทธ๋๋จธ์ค์ ๊ฐ๋ฐ์ ๋ง์ถคํ ํ๋กํ์ ๋ฑ๋กํ๊ณ , ๋์ ๊ธฐ์ ๊ถํฉ์ด ์ ๋ง๋ ๊ธฐ์ ๋ค์ ๋งค์นญ ๋ฐ์ผ์ธ์.
programmers.co.kr
์ซ์(num), ์ฐ์ฐ์(op)๋ฅผ ๋ถ๋ฆฌํด์ฃผ๊ณ ์ฐ์ฐ์ ์ฐ์ ์์ ๋ฆฌ์คํธ(per)๋ฅผ ์์ด์ ํตํด ๋ง๋ค์ด์ค๋ค.
per์ ์์๋๋ก ๋๋ฉด์ ๊ฐ ์ฐ์ฐ์์ ๋ํด ๊ณ์ฐ์ ํด์ฃผ๊ณ ,
(์ฐ์ฐ์์ ๊ฐ์๋ ํญ์ ์ซ์์ ๊ฐ์๋ณด๋ค ํ๋ ์ ์, ์ฐ์ฐ์์ idx -> ์ซ์[idx]์ ์ซ์[idx+1]์ ์ฐ์ฐ์ ์ํํ๋ฉด ๋จ)
๊ฐ ์ฐ์ ์์์ ๋ฐ๋ผ ์ ๋๊ฐ์ ์ต๋๊ฐ์ ๊ฐฑ์ ํด์ฃผ๋ฉด ๋๋ค.
# ํ๋ก๊ทธ๋๋จธ์ค 67257: ์์ ์ต๋ํ (2020 ์นด์นด์ค ์ธํด์ญ)
import re
from itertools import permutations
def solution(expression):
num = list(map(int, re.split('\+|\-|\*', expression))) # ์ซ์
op = re.split('[0-9]+', expression)[1:-1] # ์ฐ์ฐ์
per = list(permutations(set(op), len(set(op)))) # ์ฐ์ฐ์ ์ฐ์ ์์
answer = 0
for p in per:
n = num[:]
o = op[:]
i = 0
while i < len(p):
while p[i] in o:
idx = o.index(p[i])
tmp = o.pop(idx)
if tmp == '+':
n[idx] += n.pop(idx+1)
elif tmp == '-':
n[idx] -= n.pop(idx+1)
else:
n[idx] *= n.pop(idx+1)
i += 1
answer = max(answer, abs(n[0]))
return answer