Development

[프로그래머스] 소수 만들기 본문

코딩테스트/Python

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

yo~og 2021. 8. 4. 11:10
반응형

내 코드

def isPrime(a,b,c):
    
    d = a+b+c
    
    cnt=0
    
    for i in range(2,d):
        if d%i==0:
            cnt+=1
        
    return 1 if cnt==0 else 0
    
def solution(nums):
    answer = 0

    for i in range(len(nums)):
        for j in range(i+1,len(nums)):
            for k in range(j+1,len(nums)):
                answer += isPrime(nums[i],nums[j],nums[k])
                
    return answer

nums안에서 3개를 뽑아서 소수인지 판별해야한다. 

nums에서 숫자 3개를 뽑는것은 삼중포문을 사용하였다. 여기서 숫자 3개를 선택한후 isPrime함수로 넘겨주면 소수인지 아닌지 판별하여 소수이면 1을 리턴 아니면 0을 리턴하게 하였다. 

 

 

다른사람 코드

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

itertools는 처음봐서 찾아봤는데.. 대박이다..!!! 조합, 순열을 계산해주는 모듈이라고 한다..

combinations로 조합리스트를 구해 cand에 합을 구해준다.

여기서 또 새로운 문법이 나온다. for... else... 구문이다! for문을 돌리면 break에 걸려 빠져나오는 경우들이 있는데 break에 걸려서 빠져나가는건지 아닌지를 판단하기 위한 문법이다. 만약 break문을 통과하지 않는다면 else가 실행되게된다.

여기서는 cand가 0이면 소수가 아니므로 break를 걸어 빠져나가게 하였다. 만약 break문에 걸리지 않는다면 소수이므로 answer에 1을 더해준다.

 

 

 

combinations, permutations


리스트를 순열과 조합을 구해준다. 확통때 했던 P와 C이다.

combinations는 조합(순서x)을 구해주고 Permutations는 순열(순서O)을 구해준다.

import itertools

chars = ['a','b','c']

c = itertools.combinations(chars,2)
p = itertools.permutations(chars,2)

print(list(c))
print(list(p))
[('a', 'b'), ('a', 'c'), ('b', 'c')]
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
반응형
Comments