๐ŸŒฑ → ๐ŸŒณ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์†Œ์ˆ˜ ์ฐพ๊ธฐ - python ๋ณธ๋ฌธ

Algorithms

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์†Œ์ˆ˜ ์ฐพ๊ธฐ - python

BAY 2023. 8. 25. 13:08
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42839

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๋ฌธ์ œ ์œ ํ˜• : ์™„์ „ํƒ์ƒ‰

๋‚œ์ด๋„ : level 2

 

์ฝ”๋“œ

๋‚ด ์ฝ”๋“œ

import itertools 

def is_prime(n):
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def remove_non_primes(arr):
    return [num for num in arr if is_prime(num)]

def solution(numbers):
    arr = []
    for i in range(1, len(numbers)+1):
        arr.extend(list(itertools.permutations(numbers, i)))
    
    li = set()
    for i in arr:
        _str = ''.join(i)
        li.add(int(_str))
    
    li = remove_non_primes(li)
    
    return len(li)
  • permutations ์‚ฌ์šฉํ•ด์„œ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜ arr์— ์ €์žฅ
  • ์ˆซ์ž๋กœ ๋ณ€ํ™˜ ํ›„ ๊ฐ™์€ ์ˆซ์ž ์‚ญ์ œ (set ์‚ฌ์šฉ)
  • remove_non_primes() ํ•จ์ˆ˜ ์‚ฌ์šฉํ•ด์„œ ์†Œ์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ฉด ์‚ญ์ œ
  • is_prime() ํ•จ์ˆ˜ ์‚ฌ์šฉํ•ด์„œ ์†Œ์ˆ˜ ์ธ์ง€ ์•„๋‹Œ์ง€ ํŒ๋ณ„

 

๋‹ค๋ฅธ ํ’€์ด

import math
def check_prime(n):
    if n < 2:
        return False

    if n == 2:
        return True

    for i in range(2, int(math.sqrt(n)) + 1):
        if (n % i) == 0:
            return False

    return True

number_set = set()
def permutation(base, array):
    if base:
        number_set.add(int(base))

    for i, s in enumerate(array):
        permutation(base + s, array[:i] + array[i+1:])

def solution(numbers):
    answer = 0

    permutation("", list(numbers))

    answer = len(list(filter(check_prime, number_set)))

    return answer

๋‚ด ํ’€์ด๋ž‘ ๋น„์Šทํ•˜๊ธด ํ•œ๋ฐ ์ด๋Ÿฐ ๋ฐฉ๋ฒ•๋„ ์žˆ๊ตฐ

728x90