itertools - 조합, 순열
itertools - 조합, 순열
조합(combinations) | 순열(permutations) |
---|---|
순서x | 순서o |
\(_nC_r\) | \(_nP_r\) |
\(\frac{n!}{(n-r)!r!}\) | \(\frac{n!}{(n-r)!}\) |
조합
n개 중에서 r개를 뽑는 경우의 수
from itertools import combinations
fruits = ['apple', 'orange', 'banana']
for coms in combinations(fruits, 2):
print(coms)
('apple', 'orange')
('apple', 'banana')
('orange', 'banana')
# combinations 구현
for i in range(len(fruits)):
for j in range(i+1, len(fruits)):
print((fruits[i], fruits[j]))
('apple', 'orange')
('apple', 'banana')
('orange', 'banana')
순열
n개 중에서 순서를 정해 r개를 뽑는 경우의 수
from itertools import permutations
fruits = ['apple', 'orange', 'banana']
for perms in permutations(fruits, 2):
print(perms)
('apple', 'orange')
('apple', 'banana')
('orange', 'apple')
('orange', 'banana')
('banana', 'apple')
('banana', 'orange')
# permutations 구현
for i in range(len(fruits)):
for j in range(len(fruits)):
if i != j:
print((fruits[i], fruits[j]))
('apple', 'orange')
('apple', 'banana')
('orange', 'apple')
('orange', 'banana')
('banana', 'apple')
('banana', 'orange')
댓글남기기