[백준]연산자 끼워넣기

Effy_ee·2023년 9월 23일
0

코딩테스트

목록 보기
57/118
import itertools

# 수식을 계산하는 함수
def calculate_expression(numbers, operators):
    result = numbers[0]
    for i in range(len(operators)):
        if operators[i] == '+':
            result += numbers[i + 1]
        elif operators[i] == '-':
            result -= numbers[i + 1]
        elif operators[i] == '*':
            result *= numbers[i + 1]
        elif operators[i] == '/':
            # 정수 나눗셈을 수행
            if result < 0:
                result = -((-result) // numbers[i + 1])
            else:
                result //= numbers[i + 1]
    return result

n = int(input())
numbers = list(map(int, input().split()))
operand_num = list(map(int, input().split()))
operands = ['+', '-', '*', '/']
operand = []

# 입력된 연산자 개수를 바탕으로 operand 리스트 생성
for i in range(4):
    operand.extend([operands[i]] * operand_num[i])

max_result = float('-inf')  # 최댓값 초기화
min_result = float('inf')   # 최솟값 초기화

# 가능한 연산자 순열을 생성하고 계산
for perm in itertools.permutations(operand, n - 1):
    result = calculate_expression(numbers, list(perm))
    max_result = max(max_result, result)
    min_result = min(min_result, result)

# 결과 출력
print(max_result)
print(min_result)

0개의 댓글