minimimi

[Python] 순열, 조합, 중복순열, 중복조합 본문

프로그래밍 공부/Python

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

99mini 2021. 9. 30. 18:00
반응형

1. 순열

 permutations(Iterable, r) 

# 순열
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(Iterable, r) 

# 조합
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)

3. 중복순열

 product(Iterable, repeat = ) 

# 중복순열
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')

for i in product(range(3), range(3), range(3)):
    print(i)
(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)

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)

 


4.중복조합

combinations_with_replacement(Iterable, r) 

# 중복조합
from itertools import combinations_with_replacement

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

 

# (1, 1) (1, 2) (1, 3) (1, 4) (2, 2) (2, 3) (2, 4) (3, 3) (3, 4) (4, 4)

 

반응형

'프로그래밍 공부 > Python' 카테고리의 다른 글

[Python] Collections 모듈: counter, most_common  (0) 2022.03.19