itertools: 조합론
순열, 조합 및 데카르트 곱을 생성합니다.
itertools: 조합론은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
조합론 개요
itertools는 네 가지 조합론 함수를 제공합니다. product, permutations, combinations, combinations_with_replacement입니다.
import itertools
# All orderings of 2 items from ABC
print(list(itertools.permutations("ABC", 2)))
# [(A,B),(A,C),(B,A),(B,C),(C,A),(C,B)]product()
product(*iterables, repeat=1)은 데카르트 곱을 계산합니다. 중첩된 for 루프를 사용하는 것과 같습니다.
import itertools
print(list(itertools.product([1,2], ["a","b"])))
# [(1,"a"),(1,"b"),(2,"a"),(2,"b")]
# repeat=2 pairs each element with itself
print(list(itertools.product(range(2), repeat=2)))
# [(0,0),(0,1),(1,0),(1,1)]permutations()
permutations(it, r)은 길이가 r인 모든 순서 있는 배열을 생성합니다. 전체 개수는 P(n,r) = n!/(n-r)!입니다.
import itertools
result = list(itertools.permutations([1,2,3], 2))
print(result)
# [(1,2),(1,3),(2,1),(2,3),(3,1),(3,2)]
print(len(result)) # 6combinations()
combinations(it, r)은 중복 없이 길이가 r인 모든 순서 없는 선택을 생성합니다. 전체 개수는 C(n,r) = n!/(r!(n-r)!)입니다.
import itertools
result = list(itertools.combinations([1,2,3,4], 2))
print(result)
# [(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]
print(len(result)) # 6combinations_with_replacement()
combinations_with_replacement(it, r)은 하나의 요소가 조합에 두 번 이상 나타나는 것을 허용합니다.
import itertools
result = list(itertools.combinations_with_replacement("AB", 2))
print(result)
# [(A,A),(A,B),(B,B)]실체화하지 않고 개수 세기
개수만 세기 위해 모든 요소를 생성하는 대신 math.perm, math.comb, 또는 len() 바로 가기를 사용하십시오(len()은 유한한 결과에서만 작동합니다).
import math
print(math.perm(10, 3)) # 720
print(math.comb(10, 3)) # 120비밀번호/키 생성
조합론 이터레이터를 사용하면 모든 후보 키나 테스트 사례를 메모리에 한꺼번에 불러오지 않고 생성할 수 있습니다.
import itertools, string
chars = string.ascii_lowercase
# All 2-char lowercase combos:
for combo in itertools.combinations(chars, 2):
pass # process without materialisingproduct로 격자 좌표 만들기
product(range(rows), range(cols))를 사용하면 중첩된 루프 없이 2차원 격자를 순회할 수 있습니다.
import itertools
for row, col in itertools.product(range(3), range(3)):
print(f"({row},{col})", end=" ")모든 부분집합 테스트하기
0부터 n까지 각 길이에 대해 combinations를 순회하면 목록의 모든 부분집합을 생성할 수 있습니다.
import itertools
items = [1, 2, 3]
all_subsets = []
for r in range(len(items)+1):
all_subsets.extend(itertools.combinations(items, r))
print(all_subsets)combinations로 중복 제거하기
combinations를 사용하면 각 요소 쌍을 정확히 한 번만 비교하여 중복된 (a,b)와 (b,a) 비교를 피할 수 있습니다.
import itertools
words = ["apple","apricot","banana","blueberry"]
for a, b in itertools.combinations(words, 2):
if a[0] == b[0]:
print(f"Same letter: {a}, {b}")성능 고려 사항
조합론적 수열은 매우 빠르게 증가합니다. permutations(range(12))은 4억 7,900만 개의 결과를 생성합니다. 항상 생성기를 사용하고 필요한 결과만 실제로 생성하십시오.
import itertools, math
n = 12
print(f"P(12,12) = {math.factorial(n):,}") # 479,001,600
# Never: list(itertools.permutations(range(12)))
# Instead: iterate lazily and break early빠른 확인
컬렉션에서 중복 없이 모든 순서 없는 쌍을 생성하는 itertools 함수는 무엇입니까?
복습
데카르트 곱에는 product, 순서 있는 배열에는 permutations, 순서 없는 부분집합에는 combinations를 사용하십시오. 요소를 반복할 수 있을 때는 combinations_with_replacement를 사용하십시오. 조합론 이터레이터는 항상 지연 방식으로 처리하십시오.
자주 묻는 질문
“itertools: 조합론” 강의는 무료인가요?
네 — “itertools: 조합론” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“itertools: 조합론”에서 뭘 배우나요?
순열, 조합 및 데카르트 곱을 생성합니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“itertools: 조합론” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.