접근 방법
9명 모두의 키의 합에서 100을 빼서 excess를 구한다.
그 다음, for문을 이용하여 9명 중 2명의 조합이 excess와 같은지 확인하고, 같을 시 print한다.
입력 코드
dwarf = []
for i in range(9):
dwarf.append(int(input().rstrip()))
dwarf.sort()
excess = sum(dwarf) - 100
for j in range(8):
for k in range(j+1,9): #확통에서 9C2하는 것과 같은 방식
if dwarf[j] + dwarf[k] == excess:
del dwarf[j]
del dwarf[k-1] #line12에서 item 하나를 del 했으므로, k가 아닌 k-1을 del해야함
for l in dwarf:
print(l)
exit()
for문을 이용하는 대신, intertools 모듈에서 combinations() 함수를 이용할 수 있다.
combinations(iterable, r) 의 구조이며, tuple 형식으로 생성되며, 순서는 iterable의 순서를 따른다.
from itertools import combinations
dwarf = []
for i in range(9):
dwarf.append(int(input().rstrip()))
for j in combinations(dwarf, 7):
if sum(j) == 100:
for k in sorted(j):
print(k)
exit()
이 외에도, itertools 모듈에는 중복조합, 순열, 데카르트곱을 생성하는 함수가 있다.
combinations(iterable, r) # 조합
combinations_with_replacement(iterable, r) # 중복조합
permutations(iterable, r=None) # 순열, r 미지정 시 iterable의 길이로 순열이 생성
rproduct(iterable, iterable, ... , repeat=1) # 데카르트곱
'Python > 문제풀이' 카테고리의 다른 글
python_백준BOJ_#2116_주사위 쌓기_review (0) | 2023.01.31 |
---|---|
python_백준BOJ_#2596_비밀편지_review (0) | 2023.01.30 |