기계는 거짓말하지 않는다

Python 순열 (Permutation) 구현 본문

Python

Python 순열 (Permutation) 구현

KillinTime 2023. 4. 15. 15:39

Python에서 재귀함수를 이용한 순열 (Permutation)이다.

def swap(arr, i1, i2):
    temp = arr[i1]
    arr[i1] = arr[i2]
    arr[i2] = temp
    
def permutation(arr, depth, n, r):
    count = 0
    
    if depth == r:
        for i in arr:
            print(i, end="")
        print("")
        
        return 1
    
    for i in range(depth, n):
        swap(arr, depth, i)
        count += permutation(arr, depth + 1, n, r)
        swap(arr, depth, i)
        
    return count
        
arr = ["A", "B", "C", "D"]
count = permutation(arr, 0, 4, 2)
print(count)

Comments