python

[Python] 순열, 조합

딸기케잌🍓 2021. 4. 6. 23:19

파이썬에서 만들어준 표준 라이브러리 itertools를 사용할 수 있다.

 

조합

combinations(iterable 객체, r)

조합을 구할 때 사용되는 메소드로 iterable 객체에서 r개를 뽑아 조합을 만든다.

한 리스트에서 중복을 허용하지 않는 모든 조합의 경우의 수를 구한다.

   from itertools import combinations
  
   mylist=[1,2,3,4]
   combi = list(combinations(mylist,2))
   print(combi)
   
   # 결과
   # [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

 

순열

permutations(iterable 객체, r)

iterable 객체에서 중복을 허용하여 r개를 뽑아 모든 경우의 수를 구한다.

   from itertools import permutations
  
    mylist=[1,2,3,4]
    permu = list(permutations(mylist,2))
    print(permu)
   
   # 결과
   # [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

'python' 카테고리의 다른 글

[Python] Map함수, Filter함수  (0) 2021.10.02
[Python] zip 함수  (0) 2021.04.01
[Python] 오름차순 정렬, 내림차순 정렬  (0) 2021.03.28
join과 split  (0) 2020.06.29
[Python] enumerate  (0) 2020.06.29