Suppose that you want to count the number of cases where a prime number is generated when adding 3 numbers among the given numbers. Given an array nums containing numbers as the parameter, write a function solution to return the number of cases where a prime number is generated when adding 3 different numbers among nums.
Constraints
- Length of nums is between 3 and 50.
- Each element of nums is a natural number between 1 and 1,000, and there are no duplicate numbers.
Examples
nums result
[1,2,3,4] | 1 |
[1,2,7,6,4] | 4 |
바로 직전 문제가 소수 가지고 장난치는 문제라 그때 쓴 코드를 거의 그냥 가져왔다
알고리즘은 다음과 같다
1. 기본 소수 판별 알고리즘을 이용한다 (is_prime 함수)
2. combination 모듈을 이용해 3개씩 뽑은 모든 조합을 만들고, 그걸 다 더한 뒤, 1번에서 만든 is_prime 함수를 호출해와 소수인지 검사한다.
3. 답이면 answer 값을 1씩 증가시킨다
#기본적인 소수판별 알고리즘
import math
def is_prime(nums):
for i in range(2, int(math.sqrt(nums))+ 1):
if nums % i == 0:
return False
return True
from itertools import *
# 조합 알고리즘
def solution(nums):
answer = 0
combi = list(combinations(nums, 3))
for i in combi:
a = sum(i)
if is_prime(a) == True:
answer += 1
return answer
728x90
'코딩테스트 > python' 카테고리의 다른 글
[python][프로그래머스_lv1] 크기가 작은 부분 문자열 (0) | 2022.12.28 |
---|---|
[python][프로그래머스_lv1] 실패율 (카카오 코딩테스트) (0) | 2022.12.27 |
[python][프로그래머스_lv1] 콜라 문제 (0) | 2022.12.24 |
[python][프로그래머스_lv1] 모의고사 (0) | 2022.12.23 |
[python][프로그래머스] 삼총사 (0) | 2022.12.11 |