반응형

파이썬 알고리즘 / combinations(), permutations() - 모든 조합, 순열 구하기

 

combinations()

- 모든 조합을 구합니다. 

- 리스트 내의 원소 순서를 고려하지 않습니다.

from itertools import combinations

list(combinations(리스트, 조합하려는 원소 갯수))

 

permutations()

- 모든 순열을 구합니다. 

- 리스트 내의 원소 순서도 고려합니다.

from itertools import permutations

list(permutations(리스트, 순열하려는 원소 갯수))

 

예제

from itertools import combinations
from itertools import permutations

a = [1 ,2 ,3 ,4 ,5 ]
p = list(combinations(a, 3))
q = list(permutations(a, 3))

print(list(p))
#[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), 
#(1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), 
#(2, 4, 5), (3, 4, 5)]

print(list(q))
#[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 2), 
#(1, 3, 4), (1, 3, 5), (1, 4, 2), (1, 4, 3), 
#(1, 4, 5), (1, 5, 2), (1, 5, 3), (1, 5, 4), 
#(2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 3, 1), 
#(2, 3, 4), (2, 3, 5), (2, 4, 1), (2, 4, 3), 
#(2, 4, 5), (2, 5, 1), (2, 5, 3), (2, 5, 4), 
#(3, 1, 2), (3, 1, 4), (3, 1, 5), (3, 2, 1), 
#(3, 2, 4), (3, 2, 5), (3, 4, 1), (3, 4, 2), 
#(3, 4, 5), (3, 5, 1), (3, 5, 2), (3, 5, 4), 
#(4, 1, 2), (4, 1, 3), (4, 1, 5), (4, 2, 1), 
#(4, 2, 3), (4, 2, 5), (4, 3, 1), (4, 3, 2), 
#(4, 3, 5), (4, 5, 1), (4, 5, 2), (4, 5, 3), 
#(5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 2, 1), 
#(5, 2, 3), (5, 2, 4), (5, 3, 1), (5, 3, 2), 
#(5, 3, 4), (5, 4, 1), (5, 4, 2), (5, 4, 3)]
반응형

+ Recent posts