Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

0과 1 사이

[파이썬(python)] 이것이 취업을 위한 코딩 테스트다 연산자 끼워 넣기 백준 14888 본문

코딩테스트

[파이썬(python)] 이것이 취업을 위한 코딩 테스트다 연산자 끼워 넣기 백준 14888

고후 2022. 2. 16. 11:28

https://www.acmicpc.net/problem/14888

 

14888번: 연산자 끼워넣기

첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 

www.acmicpc.net

 

내 코드..

실패 ㅜ

import math
from itertools import product

n = int(input())
a = list(map(int, input().split()))
plus, minus, multiple, divide = map(int, input().split())
result = []


pro = list(product(['+','-','*','/'], repeat = n-1))
            
for case in pro:
    result_now = a[0]
    for r in range(1, n):
        if case[r-1] == '+':
            result_now += a[r]
        elif case[r-1] == '-':
            result_now -= a[r]
        elif case[r-1] == '*':
            result_now *= a[r]
        elif case[r-1] == '/':
            result_now = int(result_now / a[r])

    result.append(result_now)
    

print(max(result))
print(min(result))

 

 

수정한 코드

약간 고민을 했던게 '+', '-', '*', '/' 전부 입력받은 만큼 product 해야하는데.. product하면 그냥 가능한 모든 조합으로 리스트에 저장된다..

그래서 저장된 리스트에서 다시 '+', '-', '*', '/'의 개수를 카운트했을 때 add, sub, mul, div만큼의 개수가 있는 case만

다른 리스트에 새로 저장했다. 

효율성이 떨어지나 고민했지만 백준에서 테스트했을 때 잘 통과된다.

 

import math
from itertools import product

n = int(input())
a = list(map(int, input().split()))
add, sub, mul, div = map(int, input().split())
result = []


pro = list(product(['+', '-', '*', '/'], repeat = n-1))
available_pro = []
for case in pro:
    if case.count('+') == add:
        if case.count('-') == sub:
            if case.count('*') == mul:
                if case.count('/') == div:
                    available_pro.append(case)
available_pro = list(set(available_pro))
    

for case in available_pro:
    result_now = a[0]
    for i in range(n-1):
        if case[i] == '+':
            result_now += a[i+1]
        elif case[i] == '-':
            result_now -= a[i+1]
        elif case[i] == '*':
            result_now *= a[i+1]
        elif case[i] == '/':
            result_now = int(result_now / a[i+1])

    result.append(result_now)
    

print(max(result))
print(min(result))
Comments