Python/Python

[Python] 순열과 조합

S0PH1A 2019. 8. 8. 15:59
반응형

[Python] 순열과 조합


하나의 리스트에서 모든 조합을 계산하는 방법

1. 순열

itertools.permutations(iterable[, r])

https://www.hackerrank.com/challenges/itertools-permutations/problem

  • iterable: iterable한 값
  • r: 몇개 씩 묶을 것인지, (미 입력 -> iterable 전체 길이)
    >>> from itertools import permutations
    >>> print list(permutations(['1','2','3']))
    [('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), ('3', '1', '2'), ('3', '2', '1')]
    >>> 
    >>> print list(permutations(['1','2','3'],2))
    [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]

 

2. 조합

itertools.combinations(iterable, r)

https://www.hackerrank.com/challenges/itertools-combinations/problem?h_r=next-challenge&h_v=zen

  • iterable: iterable한 값
  • r: 몇개 씩 묶을 것인지
    >>> from itertools import combinations
    >>> print list(combinations('12345',2))
    [('1', '2'), ('1', '3'), ('1', '4'), ('1', '5'), ('2', '3'), ('2', '4'), ('2', '5'), ('3', '4'), ('3', '5'), ('4', '5')]
    >>> 
    >>> A = [1,1,3,3,3]
    >>> print list(combinations(A,4))
    [(1, 1, 3, 3), (1, 1, 3, 3), (1, 1, 3, 3), (1, 3, 3, 3), (1, 3, 3, 3)]
반응형