데이터분석 study/Python

TIL_24.07.26_itertools/combinations

justdata 2024. 7. 26. 15:19

아침에 알고리즘 코드카타를 풀고, 

다른 분들 풀이를 보다가 발견한 

itertools 모듈에 combinations 함수를 알게 되었다.

https://docs.python.org/3/library/itertools.html

 

itertools — Functions creating iterators for efficient looping

This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...

docs.python.org

 

 

combinations(iterable,r)

     - iterable 에서 원소 개수가 r개인 조합 뽑기

 

예시)

프로그래머스 문제를 링크로 달고 코드를 보면 

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

 

코드출처 : https://real-myeong.tistory.com/145

 

[Python] 삼총사

https://school.programmers.co.kr/learn/courses/30/lessons/131705 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞

real-myeong.tistory.com

 

from itertools import combinations # 조합 

def solution(number):
    
    answer = 0
    
    for i in combinations(number, 3): 
        if sum(i) == 0 : 
            answer += 1 
    
    return answer

 

 

 

문제를 보자면 ,

한국 중학교 학생들의 번호를 나타내는 정수 배열 number가 매개변수로 주어질 때, 

이 학교 학생 3명의 정수번호를 더했을 때 0이 되면 삼총사가 된다.

예를 들어 5명의 학생이 있는데 번호가 순서대로 -2,3,0,2,-5 일 때 

첫 번째, 세 번째, 네 번째 학생의 정수번호를 더하면 0이므로 

세 학생은 삼총사다.

 

1. solution 사용자 정의 함수에 정수 배열 number라는 매개변수를 넣는다.

 

2. i 라는 변수에 combinations 함수로 number라는 정수 배열에서 3개를 뽑아     조합하여 담는다.

 

3. 여기서 학생 3명의 정수 번호를 더했을 때 0이 되면 삼총사가 된다고 했으므로

if sum(i) == 0

      4. 3개의 조합을 뽑아 i라는 변수에 담아서 다 더했을 때 answer라는 변수에 1씩 더 해준다.

   

answer += 1

 

5. 그렇게 해서 answer 을 반환.