Scribbling

프로그래머스: 소수 찾기 본문

Computer Science/Coding Test

프로그래머스: 소수 찾기

focalpoint 2021. 10. 19. 23:05
def solution(numbers):
    def is_prime(number):
        if number == 1:
            return False
        i = 2
        while i * i <= number:
            if number % i == 0:
                return False
            i += 1
        return True
    
    def dfs(numbers, temp):
        nonlocal answer
        if temp:
            num = int(temp)
            if is_prime(num):
                answer += 1
        
        if not numbers:
            return
        
        if not temp:
            checked = None
            for i, num in enumerate(numbers):
                if num != 0 and num != checked:
                    dfs(numbers[:i]+numbers[i+1:], temp+str(num))
                    checked = num
        
        else:
            checked = None
            for i, num in enumerate(numbers):
                if num != checked:
                    dfs(numbers[:i]+numbers[i+1:], temp+str(num))
                    checked = num
        
    numbers = list(map(int, list(numbers)))
    numbers.sort()
    answer = 0
    dfs(numbers, '')
    return answer