Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 |
Tags
- MYSQL
- 재귀
- 파이썬
- 코딩테스트
- 구현
- dfs
- 수학
- 프로그래머스
- 그리디
- 브루트포스
- 스택
- BFS
- programmers
- 가상메모리 관리
- 힙
- level1
- dict
- 운영체제
- level2
- 가상메모리
- N과M
- DP
- python
- BOJ
- 다익스트라
- 다이나믹 프로그래밍
- 백준
- 딕셔너리
- level0
- level3
Archives
- Today
- Total
동캄의 코딩도장
프로그래머스 level2 [수식 최대화] 파이썬 본문
https://programmers.co.kr/learn/courses/30/lessons/67257
#프로그래머스 수식 최대화
def solution(expression):
from itertools import permutations
answer = 0
lst=[]
j=0
for i in range(len(expression)):
if not expression[i].isdigit():
lst.append(expression[j:i])
lst.append(expression[i])
j=i+1
lst.append((expression[j:]))
permu=permutations([1,2,3],3)
for a,b,c in permu:
p={'+':a,'-':b,'*':c}
number=[]
symbol=[]
for val in lst:
if val.isdigit():
number.append(int(val))
else:
if symbol:
if p[symbol[-1]]>=p[val]:
while symbol and p[symbol[-1]]>=p[val]:
x=symbol.pop()
r=number.pop()
l=number.pop()
if p[x]==a:
number.append(l+r)
elif p[x]==b:
number.append(l-r)
elif p[x]==c:
number.append(l*r)
symbol.append(val)
while symbol:
x=symbol.pop()
r=number.pop()
l=number.pop()
if p[x]==a:
number.append(l+r)
elif p[x]==b:
number.append(l-r)
elif p[x]==c:
number.append(l*r)
answer=max(answer,abs(number[0]))
return answer
먼저, 수식을 분리하고, permutation 함수를 이용해서 연산자 (+,-,*)의 우선순위를 정해준다. 각 연산을 실행하면서, 자기보다 우선순위가 큰 연산자가 오면, 작은 연산자가 나오거나 symbol리스트가 빌 때까지 연산자와 숫자를 pop 하여 연산한다.
answer에 가장 큰 절댓값을 대입한다.
'코테 > 프로그래머스' 카테고리의 다른 글
프로그래머스 level3 [등굣길] 파이썬 (0) | 2022.01.10 |
---|---|
프로그래머스 level2 [n^2 배열 자르기] 파이썬 (0) | 2021.12.24 |
프로그래머스 level2 [메뉴 리뉴얼] 파이썬 (0) | 2021.12.23 |
프로그래머스 level2 [배달] 파이썬 (0) | 2021.12.23 |
프로그래머스 level2 [뉴스 클러스터링] 파이썬 (0) | 2021.12.18 |