[python] 순열, 조합 구현하기

bird.j·2022년 8월 14일
0

python

목록 보기
10/10

재귀 함수로 구현하는데, 한 가지 원소를 뽑고 그 원소를 제외한 리스트로 조합 혹은 순열을 구하는 것이다.





조합(Combination)

combination([1,2,3,4],2)
= ([1] + combination([2,3,4],1)) and ([2] + combination([3,4],1)) and ([3] + combination([4],1))

combination([1,2,3,4], 3)
= ([1] + combination([2,3,4], 2)) and ([2] + combination([3,4], 2))
([2]+combination([3,4]), 1)


def combination(arr, r): # 배열 arr 중 r개를 뽑는 조합.
    result = []

    if r == 0:
        return [[]]

    for i in range(len(arr)):
        p = arr[i]
        for ele in def combination(arr, r): # 배열 arr 중 r개를 뽑는 조합.
(arr[i+1:], r-1):
            result.append([p] + ele)
    
    return result




순열(Permutation)

permutation([1,2,3,4],2)
= ([1] + permutation([2,3,4],1)) and ([2] + permutation([1,3,4],1)) and ([3] + permutation([1,2,4],1)) and ([4] + permutation([1,2,3],1))

def permutation(arr, r): # 배열 arr 중 r개를 뽑는 조합.
    result = []

    if r == 0:
        return [[]]

    for i in range(len(arr)):
        p = arr[i]
        for ele in permutation(arr[:i]+arr[i+1:], r-1):
            result.append([p] + ele)
    
    return result

0개의 댓글