python 메모

[python] itertools

Fine애플 2021. 5. 6. 18:28

1) itertools.product()

itertools.product()는 두개 이상의 리스트(or 집합) 끼리의 데카르트 곱(cartesian product)를 계산하여 iterator로 반환해준다. Cartesian Product는 아래와 같이 정의된다.

$$ A \times B = \{(x,y) | \ x \in A \ and \ y \in B \} $$

import itertools

A = [1,2,3]
list(itertools.product(A, repeat=2))
>>>> [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

print(itertools.product(A, repeat=2))
>>>> <itertools.product object at 0x7fa24fddc7e0>

A = [[1,2,3], [4, 5]]
list(itertools.product(*A))
>>>> [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]

A = [1,2,3]
B = [4,5]
print(itertools.product(A, B))
>>>> <itertools.product object at 0x7fa24fddc7e0>

 

2) itertools.permutations()

itertools.permutations($iterable$, $r$)은 $iterable$ 객체 원소들의 길의 $r$ 짜리 permutation을 계산하여 iterator로 반환해준다.

$$nPr = \frac{n!}{(n-r)!}$$

import itertools

A = [1,2,3]
list(itertools.permutations(A))
>>>> [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

print(itertools.product(A, repeat=2))
>>>> <itertools.permutations object at 0x7fa24fb391a8>

B = 'abc'
list(itertools.permutations(B))
>>>> [('a', 'b', 'c'),
      ('a', 'c', 'b'),
      ('b', 'a', 'c'),
      ('b', 'c', 'a'),
      ('c', 'a', 'b'),
      ('c', 'b', 'a')]

list(itertools.permutations(B, 2))
>>>> [('a', 'b'),
      ('a', 'c'),
      ('b', 'a'),
      ('b', 'c'), 
      ('c', 'a'),
      ('c', 'b')]

 

3) itertools.combinations()

itertools.combinations($iterable$, $r$)은 $iterable$ 객체 원소들의 길의 $r$ 짜리 combination들을 계산하여 iterator로 반환해준다.($r$은 필수 keyword)

$$nCr = \frac{n!}{r!(n-r)!}$$

import itertools

A = [1,2,3]
list(itertools.combinations(A, 2))
>>>> [(1, 2), (1, 3), (2, 3)]

B = 'abcde'
list(itertools.combinations(B, 3))
>>>> [('a', 'b', 'c'),
      ('a', 'b', 'd'),
      ('a', 'b', 'e'),
      ('a', 'c', 'd'),
      ('a', 'c', 'e'),
      ('a', 'd', 'e'),
      ('b', 'c', 'd'),
      ('b', 'c', 'e'),
      ('b', 'd', 'e'),
      ('c', 'd', 'e')]

 

4) itertools.combinations_with_replacement(): 중복조합

itertools.combinations_with_replacement($iterable$, $r$)은 $iterable$ 객체 원소들의 길의 $r$ 짜리 combination들을 계산하는데, 중복을 허용하여 뽑는다. 즉 itertools.combinations()와는 다르게 자기자신이 다시 뽑히는 것도 허용한다.

$$nHr = n+r-1Cr$$

import itertools

A = [1,2,3]
list(itertools.combinations(A, 2))
>>>> [(1, 2), (1, 3), (2, 3)]

list(itertools.combinations_with_replacement(A, 2))
>>>> [(1, 1), (1, 2), (1, 3), (2, 2), (2, 3), (3, 3)]

 

728x90