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
- 백준 16236
- 백준 15685
- spring cloud
- MSA
- springboot
- MySQL
- JVM
- with recursive
- 백준 16719
- 파이썬
- 백준 17779
- 백준
- spring security
- 프로래머스
- 백준 17626
- Coroutine
- Spring Boot
- JPA
- 웹어플리케이션 서버
- 백준 19238
- Spring
- 백준 16235
- java 기술면접
- 프로그래머스
- spring oauth
- Kotlin
- re.split
- sql 기술면접
- 백준 파이썬
- java
Archives
- Today
- Total
시작이 반
[프로그래머스] 수식 최대화(python 파이썬) 본문
SMALL
programmers.co.kr/learn/courses/30/lessons/67257
코딩테스트 연습 - 수식 최대화
IT 벤처 회사를 운영하고 있는 라이언은 매년 사내 해커톤 대회를 개최하여 우승자에게 상금을 지급하고 있습니다. 이번 대회에서는 우승자에게 지급되는 상금을 이전 대회와는 다르게 다음과
programmers.co.kr
순열 문제이다.
사실 최대 조합이 3! 이기때문에 내장된 permutation 함수를 써도 시간초과가 안나오는거같다...
그리고 eval라는 함수가 있는데 이 함수는 문자열 식에 대해서 계산을 해주는 함수인데 알고있었지만 쓰지 않도록 하고있는데 답을보니까 써도 시간초과가 나지 않는가보다..
permutation을 백트래킹을 이용하여 구하였고 문자열 계산은 stack을 이용하여 계산하였다.
rank = list()
max_sum = 0
def solution(expression):
oper = list()
if '*' in expression:
oper.append('*')
if '+' in expression:
oper.append('+')
if '-' in expression:
oper.append('-')
visited = [False] * len(oper)
permutation(visited, 0, expression, oper)
return max_sum
def permutation(visited: list, depth, expression, oper):
if len(visited) == depth:
calcul(rank, expression)
return
for i in range(len(visited)):
if visited[i]:
continue
visited[i] = True
rank.append(oper[i])
permutation(visited, depth + 1, expression, oper)
rank.pop()
visited[i] = False
def calcul(rank, expression):
global max_sum
expression_split = list()
temp = ''
for s in expression:
if s == '*' or s == '+' or s == '-':
expression_split.append(temp)
temp = ''
expression_split.append(s)
else:
temp += s
expression_split.append(temp)
result = list()
for i in range(len(rank)):
check = False
if i > 0:
expression_split = result
result = list()
for j in range(len(expression_split)):
if expression_split[j] == rank[i]:
result.append(expression_split[j])
check = True
else:
if check:
right = int(expression_split[j])
op = result.pop()
left = result.pop()
if op == '*':
result.append(left * right)
elif op == '+':
result.append(left + right)
elif op == '-':
result.append(left - right)
check = False
else:
if expression_split[j] == '*' or expression_split[j] == '+' or expression_split[j] == '-':
result.append(expression_split[j])
else:
result.append(int(expression_split[j]))
max_sum = max(max_sum, abs(result.pop()))
내장함수 eval와 permutation를 사용한 풀이
정규표현식을 사용하여 숫자를 제외한 문자를 그룹화 하여 split
expression = re.split('([^0-9])', expression)
import re
from itertools import permutations
def solution(expression):
oper = list()
if '*' in expression:
oper.append('*')
if '+' in expression:
oper.append('+')
if '-' in expression:
oper.append('-')
oper = list(permutations(oper))
expression = re.split('([^0-9])', expression)
max_sum = 0
for ops in oper:
expression_copy = expression[:]
for op in ops:
while op in expression_copy:
op_idx = expression_copy.index(op)
cal = str(eval(expression_copy[op_idx-1] + expression_copy[op_idx] +expression_copy[op_idx+1]))
expression_copy[op_idx-1] = cal
expression_copy = expression_copy[:op_idx] + expression_copy[op_idx+2:]
max_sum = max(max_sum, abs((int(expression_copy[-1]))))
return max_sum
LIST
'알고리즘 > Programmers' 카테고리의 다른 글
[프로그래머스] 문자열 압축 (Java 자바) (0) | 2021.08.19 |
---|---|
[프로그래머스] 보석 쇼핑(python 파이썬) (0) | 2021.04.29 |
[프로그래머스] 키패드 누르기(python 파이썬) (0) | 2021.04.29 |
[프로그래머스] 순위 검색(python 파이썬) (2) | 2021.03.19 |
[프로그래머스] 메뉴 리뉴얼(python 파이썬) (0) | 2021.03.18 |