goblin
리니팅
goblin

공지사항

전체 방문자
오늘
어제
  • 분류 전체보기 (75)
    • 개발 (31)
      • Spring (12)
      • JPA (4)
      • JAVA (4)
      • Python (6)
      • Docker (1)
      • Error (3)
      • Spring Cloud로 개발하는 MSA (1)
    • 알고리즘 (32)
    • 자료구조 (3)
    • 컴퓨터 개론 (3)
    • 개인 프로젝트 (4)
      • 쇼핑몰 만들기 (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

태그

  • dp
  • 코딩테스트
  • 스프링
  • 객체
  • JPA
  • Spring
  • 다이나믹 프로그래밍
  • 알고리즘
  • 정렬
  • 조합
  • inflearn
  • 백준
  • 파워자바
  • 프로그래머스
  • python
  • 파이썬
  • Intellij
  • 자료구조
  • tdd
  • 문자열
  • 다이나믹프로그래밍
  • BOJ
  • 구현
  • springboot
  • gradle
  • 스프링부트
  • 클래스
  • 동적계획법
  • 코딩테스트연습
  • sorting

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
goblin

리니팅

개발/Python

[Pyhton/파이썬] 순열과 조합

2022. 5. 14. 20:45
728x90

알고리즘 문제를 풀다보면 순열과 조합을 쓸 일이 꽤 많다.

물론 없이도 풀 수 있겠지만 itertools 라이브러리를 사용하면 간단하게 구현이 가능하다!

import itertools

 

순열

서로 다른 n개 중 r개를 나열하는 경우의 수이다.

import itertools
arr=[1,2,3,4]
per=itertools.permutations(arr,2)

for ele in per:
    print(ele)

"""
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
"""

 

중복 순열

중복 가능한 n개 중에 r개를 나열하는 경우의 수이다.

import itertools
arr=[1,2,3,4]
pro=itertools.product(arr,repeat=2)

for ele in pro:
    print(ele)


"""
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 1)
(3, 2)
(3, 3)
(3, 4)
(4, 1)
(4, 2)
(4, 3)
(4, 4)
"""

 

조합

서로 다른 n개 중 r개를 선택하는 경우의 수이다. (원소의 순서는 고려하지 않는다.)

import itertools
arr=[1,2,3,4]
com=itertools.combinations(arr,3)

for ele in com:
    print(ele)

"""
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
"""

 

중복 조합

중복 가능한 n개 중 r개를 선택하는 경우의 수이다. (원소의 순서는 고려하지 않는다.)

import itertools
arr=[1,2,3,4]
com=itertools.combinations_with_replacement(arr,2)

for ele in com:
    print(ele)

"""
(1, 1)
(1, 2)
(1, 3)
(1, 4)
(2, 2)
(2, 3)
(2, 4)
(3, 3)
(3, 4)
(4, 4)
"""
728x90
반응형

'개발 > Python' 카테고리의 다른 글

[Python] 데크(deque)  (0) 2022.05.13
[파이썬] find, index 함수  (0) 2022.01.13
[Python] sort(), sorted(), lambda  (0) 2022.01.12
[파이썬] collections 모듈 - Counter (사용빈도 확인)  (0) 2021.12.27
[파이썬] 올림, 내림, 반올림  (0) 2021.12.27
    '개발/Python' 카테고리의 다른 글
    • [Python] 데크(deque)
    • [파이썬] find, index 함수
    • [Python] sort(), sorted(), lambda
    • [파이썬] collections 모듈 - Counter (사용빈도 확인)
    goblin
    goblin

    티스토리툴바