티스토리 뷰
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
from itertools import permutations
# 수식 숫자와 연산자로 분리
def sep_num_op(expression):
nums, ops = [], []
num = ""
for s in expression:
if s.isdigit(): # 숫자면
num += s
else: # 연산자면
nums.append(num)
num = ""
ops.append(s)
nums.append(num)
return nums, ops
# 주어진 숫자와 연산자를 사용해 우선순위에 따라 계산
def calculate(temp_nums, temp_ops, priority):
for op in priority:
i = 0
while i < len(temp_ops):
if temp_ops[i] == op:
new_expr = temp_nums[i] + op + temp_nums[i + 1]
temp_nums[i] = str(eval(new_expr))
del temp_nums[i + 1]
del temp_ops[i]
else:
i += 1
return abs(int(temp_nums[0]))
# 최대값 출력
def solution(expression):
ops = ['+', '-', '*']
# 가능한 모든 연산자 우선순위 조합
priorities = list(permutations(ops))
max_result = 0
nums, ops = sep_num_op(expression)
for priority in priorities:
temp_nums = nums.copy()
temp_ops = ops.copy()
result = calculate(temp_nums, temp_ops, priority)
max_result = max(max_result, result)
return max_result
'개발자를 위한 한 걸음 > 코딩 문제' 카테고리의 다른 글
그래프 탐색 - 백준 #14217, 골드5, 그래프/너비 우선 탐색 (0) | 2023.04.28 |
---|---|
섬의 개수 - 백준 #4963, 실버2, 그래프/bfs/dfs (0) | 2023.04.16 |
톱니바퀴 - 백준 #14891, 골드5, 구현/시뮬레이션 (0) | 2023.04.14 |
괄호 변환 - 프로그래머스 lv.2 (0) | 2023.04.14 |
인구 이동 - 백준 #16234, 골드5, 구현/그래프/너비우선탐색/시뮬레이션 (0) | 2023.04.14 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 카카오 코딩테스트
- 구현
- 브루트포스 알고리즘
- 골드5
- 그리디 알고리즘
- 시뮬레이션
- 너비 우선 탐색
- 릿코드
- lv.3
- 백준
- 코딩테스트
- 카카오
- lv.2
- 코딩 테스트
- 다이나믹 프로그래밍
- Simulation
- 그래프 탐색
- 리트코드
- 그래프 이론
- 수학
- 실버2
- 프로그래머스
- 실버3
- 깊이 우선 탐색
- leetcode
- 정렬
- 코드트리
- Python
- 백트래킹
- 문자열
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
31 |
글 보관함