🔷 permutations
itertools.permutations(iterable, r)
iterable 중에 r개의 요소를 중복 없이 뽑은 순열
🔷 combinations
itertools.combinations(iterable, r)
iterable 중에 r개의 요소를 중복 없이 뽑은 조합
🔷 combinations_with_replacement
itertools.combinations_with_replacement(iterable, r)
iterable 중에 r개의 요소를 중복 허용하여 뽑은 조합
위 세개 함수 사용 예)
1
2
3
4
5
6
7
8
9
10
|
import itertools
nums = [1,2,3]
print(list(itertools.permutations(nums, 2)))
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]
print(list(itertools.combinations(nums, 2)))
# [(1, 2), (1, 3), (2, 3)]
print(list(itertools.combinations_with_replacement(nums, 2)))
# [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]
|
cs |
🔷 product
itertools.product(*iterables, repeat=1)
iterables의 데카르트의 곱
* 데카르트의 곱 : 각 집합의 원소를 각 성분으로 하는 튜플들의 집합
product 함수 사용 예)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
import itertools
nums = [1,2,3]
"""nums, ab에서 각각 원소 하나씩 뽑는 경우"""
print(list(itertools.product(nums,'ab')))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
"""nums, ab, 가나에서 각각 원소 하나씩 뽑는 경우"""
print(list(itertools.product(nums,'ab', '가나')))
# [(1, 'a', '가'), (1, 'a', '나'), (1, 'b', '가'), (1, 'b', '나'), (2, 'a', '가'), (2, 'a', '나'), (2, 'b', '가'), (2, 'b', '나'), (3, 'a', '가'), (3, 'a', '나'), (3, 'b', '가'), (3, 'b', '나')]
"""nums, ab에서 각각 원소 하나씩 뽑는 것 두번 반복한 경우"""
print(list(itertools.product(nums,'ab', repeat=2)))
# [(1, 'a', 1, 'a'), (1, 'a', 1, 'b'), (1, 'a', 2, 'a'), (1, 'a', 2, 'b'), ... , (3, 'b', 2, 'b'), (3, 'b', 3, 'a'), (3, 'b', 3, 'b')]
"""nums에서 원소 두개 뽑는 중복 허용 순열"""
print(list(itertools.product(nums, repeat=2)))
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
|
cs |
'프로그래밍 > Python' 카테고리의 다른 글
백준_python 1931번 회의실 배정 (리스트 정렬) (0) | 2024.05.31 |
---|---|
백준_python 11726번 2×n 타일링(DP) (0) | 2024.05.27 |
백준_python 16953번 A → B (BFS, 그래프 깊이) (1) | 2024.05.20 |
백준_python 2468번 안전 영역 (BFS, DFS, 부르트포스 그래프) (0) | 2024.05.13 |
백준_python 7576번 토마토 (그래프, BFS) (0) | 2024.05.09 |