coding test - python/Programmers

Programmers / 소수 만들기 / Python

sillon 2022. 4. 5. 18:02
728x90
반응형

 

*문제 출처는 프로그래머스에 있습니다.

문제 제목: 소수 만들기

문제 사이트: https://programmers.co.kr/learn/courses/30/lessons/12977


나의 풀이

def solution(nums):
    a = []
    cnt = 0
    for i in range(0, len(nums) - 2): # 리스트의 숫자 세개를 고름(조합)
        for j in range(i + 1, len(nums) - 1):
            for x in range(j + 1, len(nums)):
                a.append(nums[i] + nums[j] + nums[x])


#약수 판별
    isPrime = True

    for x in a:
        for i in range(2,x//2+1): 
            if x % i == 0:
                isPrime = False
                break #약수가 있으면 False를 반환, 후에 break
            else:
                isPrime = True
                
        if isPrime == True:
            cnt += 1
    return cnt

 

모범답안

def solution(nums):
    from itertools import combinations as cb
    answer = 0
    for a in cb(nums, 3):
        cand = sum(a)
        for j in range(2, cand):
            if cand%j==0:
                break
        else:
            answer += 1
    return answer

from itertools import combinations as cb 

combinations을 이용하면리스트 모든 조합을 구할 수 있다.

 

itertools 라이브러리 참조 사이트

https://seu11ee.tistory.com/5

https://yganalyst.github.io/etc/memo_18_itertools/

 

[Python] itertools, 원소의 경우의 수(순열, 조합) 추출하기

itertools 라이브러리를 활용해서 원소들의 경우의 수를 추출하는 방법을 배워보자.

yganalyst.github.io


※ 알아야 할 것

- itertools 를 활용해보자

 

 

728x90
반응형