Learn to share,Share to learn
14888 파이썬 - 무한으로 최대값 설정하기, 순열 본문
N =int(input())
num = []*(N+1)
str = []*N
for _ in range(N):
num.append(map(int,input().split()))
sum = num[0]
for _ in range(int(input())):
str.append('+')
for _ in range(int(input())):
str.append('-')
for _ in range(int(input())):
str.append('*')
for _ in range(int(input())):
str.append('/')
#str 배열을 만들어서 (+ + - * /) 이런식으로 만들고 콤비네이션을 이용하여 (혹은 순열?)배치한다음 계산하기? 근데 그러면 어떻게 해야 계산을 시킬수있지
#순열을 이용해서 순서 정한 다음 나열된 str[]배열 이용하고 for문돌면서 연사자 값따라 계산해야
for i in range(1,N):
sum=num[i-1] str[i](+-*/등) num[i]
#이러고 sum의 max값 min값 찾기
브레인 스토밍
from itertools import permutations
# 숫자 입력 받기
N = int(input())
nums = list(map(int, input().split()))
# 연산자 입력 받기
add, sub, mul, div = map(int, input().split())
operators = ['+'] * add + ['-'] * sub + ['*'] * mul + ['/'] * div
# 가능한 모든 연산자 조합 생성
op_combinations = set(permutations(operators, N - 1))
# 계산 실행 및 결과 찾기
max_result = float("-inf")
min_result = float("inf")
for ops in op_combinations:
result = nums[0]
for i in range(1, N):
if ops[i - 1] == '+':
result += nums[i]
elif ops[i - 1] == '-':
result -= nums[i]
elif ops[i - 1] == '*':
result *= nums[i]
else: # 나눗셈
if result < 0:
result = -(-result // nums[i]) # 음수 나눗셈 처리
else:
result //= nums[i]
max_result = max(max_result, result)
min_result = min(min_result, result)
# 결과 출력
print(max_result)
print(min_result)
최종 코드
1. 최대 최소값에 1e9 넣었다가 오류 날수있음. 그냥 float("inf") 사용해야
2. operators = ['+'] * add + ['-'] * sub + ['*'] * mul + ['/'] * div
와 같이 연산자 입력 받을수 있다.
3.
set(permutations(operators, N - 1))
- permutations(operators, N - 1): 이 함수는 itertools 모듈의 permutations 함수를 사용하여, operators 리스트 내의 요소들로 만들 수 있는 길이가 N - 1인 모든 가능한 순열(조합)을 생성합니다.
- set(...): 생성된 순열들을 set으로 변환하여 중복을 제거합니다. 같은 연산자 조합이 여러 번 나타날 수 있기 때문에, 각 조합을 유일하게 만들기 위해 set을 사용합니다.
예를 들어, 만약 operators가 ['+', '+', '-', '*']이고 N이 5라면, permutations(operators, 4)는 이 연산자들로 만들 수 있는 모든 4개의 조합을 생성합니다. 그러나 같은 연산자 조합이 여러 번 나타날 수 있으므로, set을 사용하여 이를 유일한 조합으로 줄입니다.
'알고리즘' 카테고리의 다른 글
특정값 존재여부 비교 - list와 set를 중심으로 (0) | 2024.01.17 |
---|---|
14052 파이썬 (0) | 2024.01.16 |
파이썬 알고리즘 팁 정리 (1) | 2024.01.10 |
2745 파이썬 - 지수연산자 (1) | 2024.01.10 |
알고리즘 정리 (0) | 2024.01.09 |