주어진 숫자 중 3개의 수를 더했을 때 소수가 되는 경우의 개수를 구하려고 합니다. 숫자들이 들어있는 배열 nums가 매개변수로 주어질 때, nums에 있는 숫자들 중 서로 다른 3개를 골라 더했을 때 소수가 되는 경우의 개수를 return 하도록 solution 함수를 완성해주세요.
nums : [1,2,3,4]
nums : [1,2,7,6,4]
result : 1
result : 4
def is_prime(x):
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
return False
return True
nums
를 홀수 odds
와 짝수 even
으로 구분합니다. 방법의 개수를 저장할 변수 count
도 지정해줍니다.odds = [n for n in nums if n%2 != 0]
even = [n for n in nums if n%2 == 0]
count = 0
itertools
의 combinations
를 이용하여 홀수 3개로 만들 수 있는 모든 조합을 구해 그 중 숫자 셋을 더해 소수가 되는 경우 count를 올립니다.
if len(odds) >= 3:
for three_odd in itertools.combinations(odds, 3):
if is_prime(sum(three_odd)):
count += 1
even
에서 2개의 짝수를 뽑아 그 둘의 조합의 합과 odds
의 홀수 1개와 순차적으로 더해가며 소수를 판별합니다.if len(odds) >= 1 and len(even) >= 2:
for odd in odds:
for two_even in itertools.combinations(even,2):
if is_prime(sum(two_even)+odd):
count += 1
import itertools
import math
def solution(nums):
def is_prime(x):
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
return False
return True
odds = [n for n in nums if n%2 != 0]
even = [n for n in nums if n%2 == 0]
#홀 홀 홀
count = 0
if len(odds) >= 3:
for three_odd in itertools.combinations(odds, 3):
if is_prime(sum(three_odd)):
count += 1
#홀 짝 짝
if len(odds) >= 1 and len(even) >= 2:
for odd in odds:
for two_even in itertools.combinations(even,2):
if is_prime(sum(two_even)+odd):
count += 1
return count