순열과 조합

야금야금 공부·2023년 4월 5일

파이썬 정리

목록 보기
5/5

조합(Combinations)

한 리스트에서 중복을 허용하지 않고 모든 경우의 수를 구하는 것

1. itertools 사용X

def combinations(arr, n):
    result = []

    if n == 0:
        return [[]]

    for i in range(0, len(arr)):
        elem = arr[i]
        rest_arr = arr[i + 1:]
        for c in combinations(rest_arr, n - 1):
            result.append([elem, *c])

    return result

arr = combinations([1, 2, 3, 4], 2)
print(arr)
# [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

2. itertools 사용

from itertools import combinations

arr = list(combinations([1, 2, 3, 4], 2))
print(arr)
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

순열(Permutations)

한 리스트에서 중복을 허용하고 모든 경우의 수를 구하는 것

1. itertools 사용X

def permutations(arr, n):
    result = []
    if n == 0:
        return [[]]

    for i, e in enumerate(arr):
        for p in permutations(arr[:i] + arr[i + 1:], n - 1):
            result += [[e] + p]

    return result

print(permutations([1, 2, 3, 4], 2))
# [[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. itertools 사용

from itertools import permutations

arr = list(permutations([1, 2, 3, 4], 2))
print(arr)
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

참고

0개의 댓글