반응형
[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)]
반응형
'Python > Python' 카테고리의 다른 글
[Python] 다양한 문자 포멧팅 방법 (0) | 2019.08.26 |
---|---|
[Python] python2, python3 둘다 설치하는 방법 (windows) (0) | 2019.08.22 |
[Python] faker 라이브러리 (0) | 2019.07.02 |
[Python] 설치된 패키지 목록 requirements.txt 만들기 (0) | 2019.05.13 |
[Python][ERROR] SSL: CERTIFICATE_VERIFY_FAILED (0) | 2019.05.06 |