[백준 14888번] 연산자 끼워넣기 - Python으로 구현하기
문제 접근
- 주어진 연산자 개수내에 적절히 연산자를 조합하여 식 결과의 최댓값, 최솟값 찾기
- itertools 의 permutations 모듈 사용하여 모든 경우의수 확인
- set 을 사용하여 중복을 제거하자
생각해볼 점
- 재귀 함수로 구현 가능해보임
오답 분석
- 음수를 나누기 하는 경우 문제에 조건에 주어진 대로 처리
from itertools import permutations as pm
n = int(input())
nums = list(map(int,input().split()))
opers = list(map(int,input().split()))
# 입력받은 명령어 저장
op=''
for idx,oper in enumerate(opers):
op+=str(idx)*oper
op=list(map(int,op))
res_list=[]
for now_op in set(pm(op,len(op))): # 경우의 수(중복 제거)
res = nums[0]
for idx in range(n-1):
if now_op[idx] == 0:
res+= nums[idx + 1]
elif now_op[idx] == 1:
res-= nums[idx + 1]
elif now_op[idx] == 2:
res *=nums[idx + 1]
elif now_op[idx] == 3:
res = res//nums[idx + 1] if res>0 else ((res*-1)//nums[idx+1])*-1 # 음수 나누기 조심
res_list.append(res)
print(max(res_list))
print(min(res_list))
* 틀린 부분이나 더 나은 방법이 있을 수 있습니다. 지적해주시면 감사하겠습니다!!
'posts' 카테고리의 다른 글
[백준 14890번] 경사로 - Python으로 구현하기 (0) | 2019.10.18 |
---|---|
[백준 14889번] 스타트와 링크 - Python으로 구현하기 (0) | 2019.10.17 |
[백준 14503번] 로봇 청소기 - Python으로 구현하기 (0) | 2019.10.17 |
[백준 14502번] 연구소 - Python으로 구현하기 (0) | 2019.10.17 |
[백준 14501번] 퇴사 - Python으로 구현하기 (0) | 2019.10.17 |