Today
Total
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
관리 메뉴

기억은 짧고 기록은 길다

[프로그래머스/Programmers] 타겟 넘버 - Python 본문

CodingTest/programmers

[프로그래머스/Programmers] 타겟 넘버 - Python

ukunV 2021. 9. 23. 13:27

Link

 

코딩테스트 연습 - 타겟 넘버

n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+

programmers.co.kr

 

Solution

해당 문제는 재귀함수를 통해 해결할 수 있다.

len(numbers) == 0 and target == 0 은 연산의 결과와 target이 같음을 나타내고

len(numbers) == 0 and target != 0 은 연산의 결과와 target이 다름을 나타낸다.

def solution(numbers, target):
    if len(numbers) == 0 and target == 0:
        return 1
    elif len(numbers) == 0 and target != 0:
        return 0
    else:
        return solution(numbers[1:], target - numbers[0]) + solution(numbers[1:], target + numbers[0])
🔑 key point: Recursive Function

 

Other Solution

해당 풀이는 product()를 사용하여 해결하였다. 풀이 하단에 product() 사용예시를 첨부할테니 참고바란다.

from itertools import product

def solution(numbers, target):
    numbers = [(x, -x) for x in numbers]

    sums = list(map(sum, product(*numbers)))

    return sums.count(target)
🔑 key point: product(*numbers)

 

  •  product()
from itertools import product

a = [1, 2, 3]

a = [(x, -x) for x in a]

a = list(product(*a))

print(a)
<output>
[(1, 2, 3), (1, 2, -3), (1, -2, 3), (1, -2, -3), (-1, 2, 3), (-1, 2, -3), (-1, -2, 3), (-1, -2, -3)]
from itertools import product

a = [1, 2, 3]

b = [4, 5, 6]

c = list(product(a, b))

print(c)
<output>
[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
Comments