Prepare > Python > Itertools > itertools.product()

2023. 7. 29. 21:26HackerRank-Python

 

itertools.product() | HackerRank

Find the cartesian product of 2 sets.

www.hackerrank.com

 

문제


Task

You are given a two lists A and B. Your task is to compute their cartesian product AXB.

 

=> 리스트 A와  B를 줄테니까 A와 B의 데카르트 곱을 구해라

 

 

 

 

코드


from itertools import product

A = list(map(int, input().split()))
B = list(map(int, input().split()))

print(
    ' '.join(str(x) for x in list(product(A,B)))
)
  • str(x) for x in list(product(A,B))) 를 어떤 형식으로 담을지 정해줘야함.
  • 문자열로 출력하고 싶어서 join을 사용

 

 

 

 

노트


 cartesian product(데카르트 곱)

  • 두 집합으로 새로운 집합을 만드는 방법
  • product(A, B)(x,y) for x in A for y in B 과 같음
  • 튜플로 리턴
from itertools import product

print list(product([1,2,3],repeat = 2)) # [1, 2, 3]리스트를 2번 반복해 만들 수 있는 조합들
# [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
from itertools import product

print list(product([1,2,3],[3,4])) # [1, 2, 3]과 [3, 4]로 가능한 조합들
# [(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]
A = [[1,2,3],[3,4,5]]
print list(product(*A)) # A로 가능한 모든 데카르트 곱 조합들
# [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 3), (3, 4), (3, 5)]
from itertools import product

B = [[1,2,3],[3,4,5],[7,8]]
print list(product(*B)) # B로 가능한 모든 데카르트 조합들
# [(1, 3, 7), (1, 3, 8), (1, 4, 7), (1, 4, 8), (1, 5, 7), (1, 5, 8), (2, 3, 7), (2, 3, 8), (2, 4, 7), (2, 4, 8), (2, 5, 7), (2, 5, 8), (3, 3, 7), (3, 3, 8), (3, 4, 7), (3, 4, 8), (3, 5, 7), (3, 5, 8)]

 

 

 

패킹 *

  • 함수가 받을 인자의 개수를 유연하게 설정
  • 매개변수 앞에 * 한 개를 붙여서 사용
  • 입력한 매개변수들을 하나의 튜플 인자로 관리
def total(*numbers):
      result = 0
      for n in numbers:
           result += n
      return result

print(total(1, 2, 3))  # 6 
print(total(1, 2, 3, 4, 5, 6, 7, 8, 9))  # 45

 

하나씩 받을 매개변수와, 여러개를 받을 수 있는 매개변수로 구분

 

def skin_care(cleansing_foam, toner, *skin_lotion):
    print('세안은', cleansing_foam)
    print('세안 후는', toner)
    print('영양&수분 공급은', skin_lotion)

skin_care('DR.G', '닥터지', '독도로션', '세럼')

"""
세안은 DR.G
세안 후는 닥터지
영양&수분 공급은 ('독도로션', '세럼')
"""
더보기

오류!

def skin_care(cleansing_foam, toner, *skin_lotion, sun_cream):
    print('세안은', cleansing_foam)
    print('세안 후는', toner)
    print('영양&수분 공급은', skin_lotion)
    print('마지막으로', sun_cream)

skin_care('DR.G', '닥터지', '독도로션', '세럼', '아이오페')

 

 

언패킹 *

여러 객체를 포함하고 있는 하나의 객체를 튜플로 풀어줌

인자 앞에 * 하나를 붙여서 사용

def sum(a, b, c):
    return a + b + c

numbers = [1, 2, 3]
print(sum(*numbers))  # 6
더보기
def sum(a, b, c):
    return a + b + c

numbers = [1, 2, 3]
print(sum(numbers))  # error

 

패킹 & 언패킹 동시 사용

def skin_care(cleansing_foam, toner, *skin_lotion):
    print('세안은', cleansing_foam)
    print('세안 후는', toner)
    print('영양&수분 공급은', *skin_lotion)


skin_care('DR.G', '닥터지', '독도로션', '세럼', '아이오페')

"""
세안은 DR.G
세안 후는 닥터지
영양&수분 공급은 독도로션 세럼 아이오페
"""

 

 

두 번째 시도

from itertools import product 

A = list(map(int, input().split()))
B = list(map(int, input().split()))

print(*(product(A, B)))
  • 언패킹으로 나타내기

 

 

 

 

참조


 

9.7. itertools — Functions creating iterators for efficient looping — Python 2.7.18 documentation

 

docs.python.org

 

HackerRank itertools.product() solution in python

HackerRank itertools.product() solution in python2, python3, and pypy, pypy3 programming language with practical program code example explaination

programs.programmingoneonone.com

 

데카르트 곱 (cartesian product)

데카르트 곱은 공집합이 아니 집합들로부터 새로운 집합을 만드는 한가지 방법입니다. 일반적으로 두 집합의 데카르트 곱을 고려하며 집합 A, B가 공집합이 아닐때 A, B의 데카르는 곱은 다음과

hanmaths.tistory.com