소수 찾기

yongju·2022년 11월 7일
0

Programmers

목록 보기
10/23
post-thumbnail

프로그래머스 레벨2 [정답율 49%]

문제

문제 정리
사용한 파라미터 :
numbers(string) : 인수로 받은 수
res(list_string) : 인수로 받은 수를 permutation을 하여 모든 케이스(순열)을 가져옴
res_int(list_int) : res를 int형으로 변환
not_decimal(list_int) : 소수가 아닌 수(0,1, 합성수) 저장
decimal(list_int) : 소수인 수 저장

사용한 기능:
itertools.permutations(수,몇개씩 가져와?) : 순열 케이스 생성
math.trunc(): 소수점 이하 버리기
math.sqrt() : 루트 만들어주기

코드

import itertools
import math

def solution(numbers):
    res, res_int, not_decimal=[], [], []
    for i in range(2,len(numbers)+1):
        res.append(list(itertools.permutations(numbers,i)))
        
    for i in range(len(res)):#0 1
        for j in range(len(res[i])):
            res_int.append(int("".join(res[i][j])))
            
    for i in range(len(numbers)):
        res_int.append(int(numbers[i]))
    res_int=list(set(res_int))
            
    for i in range(len(res_int)):
        if res_int[i]<2:
            not_decimal.append(res_int[i])
        else:
            for x in range(2,math.trunc(math.sqrt(res_int[i]))+1):
                if (res_int[i]%10)==res_int[i]:#일의 자리일경우
                    if res_int[i]%x==0 and res_int[i]!=2:
                        not_decimal.append(res_int[i])

                else:#일의 자리 이상일 경우
                    if res_int[i]%x==0 :#소수가 아닐때
                        not_decimal.append(res_int[i])
                        
    decimal=set(res_int)-set(not_decimal)
    
    return len(decimal)

코드 설명

    res, res_int, not_decimal=[], [], []
    for i in range(2,len(numbers)+1):
        res.append(list(itertools.permutations(numbers,i)))

사용할 파라미터 선언 및 수 2개로 이루어진 순열부터 받은 numbers의 길이까지 모든 순열 조합을 가져옴

    for i in range(len(res)):#0 1
        for j in range(len(res[i])):
            res_int.append(int("".join(res[i][j])))

string인 res를 join하여 int형인 숫자로 만듦.

    for i in range(len(numbers)):
        res_int.append(int(numbers[i]))
    res_int=list(set(res_int))

한 자리 수도 resint에 저장한 후, set_을 이용하여 중복제거

for i in range(len(res_int)):
        if res_int[i]<2:
            not_decimal.append(res_int[i])

0또는 1이면, 소수가 아닌 not_decimal에 저장.

else:
            for x in range(2,math.trunc(math.sqrt(res_int[i]))+1):
                if (res_int[i]%10)==res_int[i]:#일의 자리일경우
                    if res_int[i]%x==0 and res_int[i]!=2:
                        not_decimal.append(res_int[i])

                else:#일의 자리 이상일 경우
                    if res_int[i]%x==0 :#소수가 아닐때
                        not_decimal.append(res_int[i])

0또는 1이 아닌 경우, 일의 자리인지 일의자리 이상인지 경우로 나누어 고려.
소수는 2부터 루트 자기자신까지의 수로 나눠지지 않은 수를 말함. 따라서, trunc, sqrt를 사용하여 루트 만들어줌.
2가 아닌 합성수를 not_decimal에 넣음.

    decimal=set(res_int)-set(not_decimal)
    
    return len(decimal)

전체 순열 케이스에서 소수가 아닌 리스트 빼서 소수인 리스트 만듦.

제출 결과

insight
사용한 테스트 케이스 : 1231, 143, 169
한글자 출력은 문자열 슬라이싱이 가능함
내림 ceil(), 올림 floor(), 소수점 버림 truck()

https://puleugo.tistory.com/76
https://blockdmask.tistory.com/522
https://ledgku.tistory.com/61

profile
AI dev

0개의 댓글