코딩테스트 연습/브루트 포스

[브루트 포스] 2309 일곱 난쟁이

멍멍코 2024. 1. 25. 21:50

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

 

2309번: 일곱 난쟁이

아홉 개의 줄에 걸쳐 난쟁이들의 키가 주어진다. 주어지는 키는 100을 넘지 않는 자연수이며, 아홉 난쟁이의 키는 모두 다르며, 가능한 정답이 여러 가지인 경우에는 아무거나 출력한다.

www.acmicpc.net


입력 처리

if __name__ == '__main__':
    dwarves = [int(sys.stdin.readline().strip()) for _ in range(9)]

9개의 줄에 걸쳐 주어지는 난쟁이의 키를 1차원 배열에 저장한다.

 

함수(일곱난쟁이 찾기)

def find_seven(dwarves):
    for seven_dwarves in combinations(dwarves, 7):
        if sum(seven_dwarves) == 100:
            return sorted(seven_dwarves)

 

'itertools' 모듈의 'combinations' 함수를 이용하여 입력받은 반복 가능한 데이터 항목들로부터 모든 가능한 조합을 생성한다.

7개의 조합을 생성하여 합을 계산하고, 100일 경우 정렬된 조합 리스트를 반환한다.

 

'combinations(iterable, r)' 함수는 다음과 같이 사용된다:

- 'iterable': 조합을 생성할 반복 가능한 데이터(예: 리스트, 문자열 등)

- 'r': 생성할 조합의 길이

 

전체 코드

import sys
from itertools import combinations

def find_seven(dwarves):
    for seven_dwarves in combinations(dwarves, 7):
        if sum(seven_dwarves) == 100:
            return sorted(seven_dwarves)

if __name__ == '__main__':
    dwarves = [int(sys.stdin.readline().strip()) for _ in range(9)]
    seven_dwarves = find_seven(dwarves)
    print(*seven_dwarves, sep='\n')