1. 정의
순열 : 몇 개를 골라 순서를 고려해 나열한 경우의 수
조합 : 몇 개를 골라 순서를 고려하지 않고 나열한 경우의 수
2. 선언
import itertools
arr = ['A', 'B', 'C']
nPr = itertools.permutations(arr, 2) ##순열
#[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
nCr = itertools.combinations(arr, 2) ##조합
#[('A', 'B'), ('A', 'C'), ('B', 'C')]
3. 기본 매소드
4. 활용
https://www.acmicpc.net/problem/14889
14889번: 스타트와 링크
예제 2의 경우에 (1, 3, 6), (2, 4, 5)로 팀을 나누면 되고, 예제 3의 경우에는 (1, 2, 4, 5), (3, 6, 7, 8)로 팀을 나누면 된다.
www.acmicpc.net
import sys
sys.stdin = open('input.txt', 'r')
# N 은 짝수이며, 두 팀으로 나눠야 한다
# 능력치
# 능력치의 차이를 최소로
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n)]
member = {ni for ni in range(n)}
answer = 1000000
import itertools
for teamA in list(itertools.combinations(member, n//2)):
scoreA, scoreB = 0, 0
teamB = member-set(teamA)
teamB = list(teamB)
# print(teamA, teamB)
for i in range(n//2-1):
for j in range(i, n//2):
scoreA += arr[teamA[i]][teamA[j]]
scoreA += arr[teamA[j]][teamA[i]]
scoreB += arr[teamB[i]][teamB[j]]
scoreB += arr[teamB[j]][teamB[i]]
answer = min(answer, abs(scoreA-scoreB))
# print(teamA, teamB)
# print(scoreA, scoreB)
print(answer)
참고1
[Python] permutation, combination 순열과 조합
Python의 itertools를 이용하면 순열과 조합을 for문 없이 구현할 수 있다.
velog.io
참고2
https://9kilometer.github.io/record/python-useful-things-for-algorithm-solve/
[PYTHON] 코딩 테스트에서 쓸만한 기능들 모음
파이썬 기본 함수나 모듈 중 코딩 테스트를 풀 때 쓸만했던 것들을 생각나는 대로 적는 중 입니다.
9kilometer.github.io
'Develop > Python' 카테고리의 다른 글
[Fastapi] 무작정 프로젝트 만들기 (0) | 2022.08.27 |
---|---|
[자료구조] | [Python] | DFS 깊이우선탐색 | BFS 너비우선탐색 (0) | 2021.08.05 |
[자료구조] [ Python ] 리스트 List 사용법 (0) | 2021.08.02 |
[ Python ] | heapq 사용법 | heapsort, 우선순위큐 (0) | 2021.08.02 |
[ Python ] | enumerate 사용법 (0) | 2021.08.01 |
댓글