python 순열, 조합

이동욱·2021년 4월 6일
0

python

목록 보기
2/2

순열, 조합 구현

순열 - 직접 구현

result = []
def permutation(arr, size, ele):
    
    if len(ele) == size:
        result.append(ele[:])
        return
    
    for i in range(len(arr)):
        ele.append(arr[i])
        temp = arr[:]
        temp.remove(arr[i])
        permutation(temp, size, ele)
        ele.pop()


permutation(range(9), 1, [])    # 1개 순열
permutation(range(9), 2, [])    # 2개 순열
permutation(range(9), 3, [])    # 3개 순열
permutation(range(9), 4, [])    # 4개 순열
permutation(range(9), 5, [])    # 5개 순열

print(result)

순열 - itertools.permutations

from itertools import permutations

9P2 = list(map(list, permutations(range(9), 2)))	# 2개 순열
9P3 = list(map(list, permutations(range(9), 3)))	# 3개 순열
9P4 = list(map(list, permutations(range(9), 4)))	# 4개 순열
9P5 = list(map(list, permutations(range(9), 5)))	# 5개 순열

조합 - 직접 구현

result = []

def combination(arr, size, ele):
    if len(ele) == size:
        result.append(ele[:])
        return
    
    for i in range(len(arr)):
        ele.append(arr[i])
        combination(arr[i+1:], size, ele)
        ele.pop()
    

combination(range(9), 1, [])   # 1개 조합
combination(range(9), 2, [])   # 2개 조합
combination(range(9), 3, [])   # 3개 조합
combination(range(9), 4, [])   # 4개 조합
combination(range(9), 5, [])   # 5개 조합

print(result)

조합 - itertools.combinations

from itertools import combinations

9C2 = list(map(list, combinations(range(9), 2)))	# 2개 조합
9C3 = list(map(list, combinations(range(9), 3)))	# 3개 조합
9C4 = list(map(list, combinations(range(9), 4)))	# 4개 조합
9C5 = list(map(list, combinations(range(9), 5)))	# 5개 조합
profile
무엇을 해야 재밌을까!

0개의 댓글