본문 바로가기
개발일지/Python

파이썬 2, 3개의 값에서 중복없이 짝을 지을 수 있는 경우의 수 코드 및 공식

by 개발에정착하고싶다 2022. 5. 11.
320x100
numbers = [4,6,7,9]
result = []

# 시작숫자인 n1은 두번째 for문으로 들어가면서 고정된다.
for n1 in numbers:
    # 그렇게 고정된 첫번째 for문에서 생성된 n1은 n1와 비교를 한다.
    for n2 in numbers:
        # 이때 n1 과 n2가 같으면 아무일 없이 넘어간다. 그리고 다시 두번째 for문의 시작으로 거슬러 올라간다.
        if n1 == n2:
            # 이걸 써줬기에 값이 같을때 거슬러 올라가는게 가능해졌다.
            continue

        result.append([n1,n2])

print(f'result: {result}')
print(f'result length: {len(result)}')

두번째.

경우의 수만 구할때

# 순열의 공식 방식으로 풀이
# 경우의 수만 구할때
# n! / (n-r)!

import math
pernutation = math.factorial(len(numbers)) / math.factorial(len(numbers) - 2)
print(int(pernutation))

 

세번째

4개의 숫자중 3개씩 짝지은 경우의 수

 

# 4개의 숫자 중 서로 다른 3개의 숫자를 짝 짓는 경우의 수
numbers = [4,6,7,9]

result = []

for n1 in numbers:
    for n2 in numbers:
        if n1 == n2: continue

        for n3 in numbers:
            if n1 == n3 or n2 ==n3: continue

            result.append([n1,n2,n3])


print(result)
print(len(result))
300x250