[Python] combinations, permutations 직접 구현

yoonene·2022년 10월 15일
0

알고리즘

목록 보기
24/62

1. combinations

combination([0,1,2,3], 2) = ([0], combination([1, 2, 3], 1)) + ([1], combination([2, 3], 1)) + ([2], combination([3], 1)))

def combinations(arr, n):    
result = []    
if n == 0:        
	return [[]]        
for i in range(len(arr)):        
	elem = arr[i]        
    for rest in combination(arr[i + 1:], n - 1):
    	result.append([elem] + rest)
return result 
print(combinations([0,1,2,3], 2))
# [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]

2. permutations

permutation([0,1,2,3], 2) = ([0], permutation([1, 2, 3], 1)) + ([1], permutation([0, 2, 3], 1)) + ([2], permutation([0, 1, 3], 1)) + ([3], permutation([0, 1, 2], 1))

def permutations(arr, n):    
result = []    
if n == 0:        
	return [[]]        
for i in range(len(arr)):        
	elem = arr[i]        
    for rest in permutations(arr[:i] + arr[i + 1:], n - 1):
    	result.append([elem] + rest)
return result 
print(combination([0,1,2,3], 2))
# [[0, 1], [0, 2], [0, 3], [1, 2], [1, 3], [2, 3]]
profile
NLP Researcher / Information Retrieval / Search

0개의 댓글