프로그래밍/Python
itertools(permutations, combinations, product) 정리
O'bin
2024. 5. 27. 20:36
🔷 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 |