상세 컨텐츠

본문 제목

[파이썬] 프로그래머스 소수 만들기

카테고리 없음

by \시엔/ 2022. 3. 26. 23:50

본문

import math
from itertools import combinations

def solution(nums):
    answer = 0
    arr = list(combinations(nums, 3))
    for array in arr:
        res = 0
        result = True
        for i in range(3):
            res += array[i]
        for i in range(2, int(math.sqrt(res) + 1)):
            if res % i == 0:
                result = False
        if result == True:
            answer += 1

    return answer

 

 

소수의 판별: 개선된 알고리즘 (Python)

import math

# 소수 판별 함수
def is_prime_number(x):
    # 2부터 x의 제곱근까지의 모든 수를 확인하며
    for i in range(2, int(math.sqrt(x)) + 1):
        # x가 해당 수로 나누어떨어진다면
        if x % i == 0:
            return False # 소수가 아님
    return True # 소수임

 

파이썬(Python)에서 리스트에 있는 값들의 모든 조합을 구하기

from itertools import combinations

items = ['1', '2', '3', '4', '5']
result = list(combinations(items, 2))

print(result)

출력 : [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]

 

하나의 리스트에 모든 조합을 계산해야 한다면 -> permutations, combinations

두 개 이상의 리스트에서 모든 조합을 계산해야 한다면 -> product