코딩테스트/Python 개념

[Python] 순열/조합 , 중복 순열/중복 조합

박소민 2022. 8. 12. 13:30
순열(permutations) / 조합 (combinations)
 itertools를 이용
  • perm= p(반복가능한 객체, 반복횟수) 받아올때 리스트에 넣을 필요없이 바로 받기
  • 반복가능한 객체: list, string 다 됨

 

 

  1. permutations(반복 가능한 객체, r)
    • 반복 가능한 객체(=길이가 n인)에 대해서 중복을 허용하지 않을 때, 순서를 고려하여 r개를 뽑아서 나열
    • 순서가 의미 있음.
      • (1,2) != (2,1)
from itertools import permutations

for i in permutations([1,2,3,4], 2):
    print(i, end=" ")
(1, 2) (1, 3) (1, 4) (2, 1) (2, 3) (2, 4) (3, 1) (3, 2) (3, 4) (4, 1) (4, 2) (4, 3) 

 

2.  combinations(반복 가능한 객체, r)

  • 반복 가능한 객체(=길이가 n인)에 대해서 중복을 허용하지 않을 때, 순서를 고려하지 않고 r개를 뽑아서 나열
  • 순서가 의미 없음.
    • (1,2) == (2,1)
from itertools import combinations

for i in combinations([1,2,3,4], 2):
    print(i, end=" ")
(1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) 

 

중복 순열(product) / 중복 조합

 

1.  중복 순열

  • product(반복 가능한 객체, repeat=1)
for i in product([1,2,3], repeat=2):
    print(i, end=" ")
(1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3) 

 

  • product(반복 가능한 객체, 반복 가능한 객체)
from itertools import product

for i in product([1,2,3],'ab'):
    print(i, end=" ")
(1, 'a') (1, 'b') (2, 'a') (2, 'b') (3, 'a') (3, 'b')

 

from itertools import product

for i in product(range(3), range(3), range(3)):
    print(i, end=" ")
(0, 0, 0) (0, 0, 1) (0, 0, 2) (0, 1, 0) (0, 1, 1) (0, 1, 2) (0, 2, 0) (0, 2, 1) (0, 2, 2)
(1, 0, 0) (1, 0, 1) (1, 0, 2) (1, 1, 0) (1, 1, 1) (1, 1, 2) (1, 2, 0) (1, 2, 1) (1, 2, 2)
(2, 0, 0) (2, 0, 1) (2, 0, 2) (2, 1, 0) (2, 1, 1) (2, 1, 2) (2, 2, 0) (2, 2, 1) (2, 2, 2)

 

 

2.  중복 조합

 

  • combinations_with_replacement(반복 가능한 객체, r)
 
from itertools import combinations_with_replacement

for cwr in combinations_with_replacement([1,2,3,4], 2):
    print(cwr, end=" ")
(1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)