반응형
프로그래머스
2020 카카오 인턴쉽
https://school.programmers.co.kr/learn/courses/30/lessons/67257
from collections import deque
from itertools import permutations
def solution(expression):
answer = 0
ops = ['*', '+', '-']
#분리, 스택 생성
nums = []
s = 0
for idx, value in enumerate(expression):
if value in ops:
nums.append(expression[s:idx])
nums.append(value)
s = idx+1
else:
nums.append(expression[s:])
stack = [deque(nums), deque()]
print(stack)
#expression에 없는 연산자 제거
for op in ops:
if op not in expression:
ops.remove(op)
possible = permutations(ops)
print(possible)
for case in possible:
stacks = [deque(nums), deque()]
t1 = 1
for c in case:
t1 = (t1+1) % 2 # 스택 토글 변수
t2 = (t1+1) % 2
while len(stacks[t1]):
item = stacks[t1].popleft()
if len(stacks[t2]) and stacks[t2][-1] == c:
c = stacks[t2].pop()
n = stacks[t2].pop()
item = str(eval(str(n)+c+str(item)))
stacks[t2].append(item)
result = stacks[len(ops)%2].pop()
result = abs(int(result))
answer = max(answer, result)
#answer = 0
return answer
반응형
'DS > Coding Test' 카테고리의 다른 글
[Python] 튜플 (0) | 2023.05.19 |
---|---|
[Python] 간단한 식 계산하기 (0) | 2023.05.19 |
[Python][정렬] H-Index (0) | 2023.05.19 |
[Python] 5명씩 (0) | 2023.05.19 |
[Python][DFS] 여행경로 (0) | 2023.05.18 |