본문 바로가기
알고리즘/함수 in python

from itertools import 순열, 조합, 곱집합, 중복조합 in python

by lucian 2021. 11. 2.

순열. import permutations -> 순서가 있음

from itertools import permutations

n,m=map(int,input().split())
#n=4, m=2
permu=list(permutations([i for i in range(1, n+1) ],m)) # [1,2,3,4], 2

print(permu)
'''
for i in permu:
  for j in range(len(i)):
    print(i[j], end=' ')
  print()
'''
 
'''
입력 : 4 2
출력 :
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]


입력 : 3 1
출력 : 
[(1,), (2,), (3,)]

입력 : 4 4
출력 : 
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]

'''

 

조합. import combinations -> 순서가 없음

from itertools import combinations

n,m = map(int,input().split())
combi=list(combinations([i for i in range(1,n+1)],m))

print(combi)
'''
for i in combi:
  for j in range(len(i)):
    print(i[j],end=' ')
  print()
'''

'''
입력 : 3 1
출력 : [(1,), (2,), (3,)]

입력 : 4 2
출력 : [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

입력 : 4 4
출력 : [(1, 2, 3, 4)]
'''

 

곱집합. import product -> 순서가 있지만 자신도 중복으로 들어감.

product는 보통 리스트 두개로 씀. 한개로 중복순열을 만들 경우는 repeat를 써줘야 한다.

from itertools import product

n,m= map(int, input().split())

prod=list(product([i for i in range(1,n+1)],repeat=m))

prod_lst_2=list(product([1,2,3,4],'ab'))

print(prod)
print(prod_lst_2)

'''
입력 : 4 2
prod 출력 : 
[(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)]
prod_lst_2 출력 : 
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b'), (4, 'a'), (4, 'b')]
'''

 

중복조합. import combinations_with_replacement -> 중복으로 수열만듬.

from itertools import combinations_with_replacement

n,m=map(int,input().split())

cwr=list(combinations_with_replacement([i for i in range(1,n+1)],m))

print(cwr)

'''
입력 : 4 2
출력 : 
[(1, 1), (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), (4, 4)]

입력 : 4 4
출력 : 
[(1, 1, 1, 1), (1, 1, 1, 2), (1, 1, 1, 3), (1, 1, 1, 4), (1, 1, 2, 2), (1, 1, 2, 3), (1, 1, 2, 4), (1, 1, 3, 3), (1, 1, 3, 4), (1, 1, 4, 4), (1, 2, 2, 2), (1, 2, 2, 3), (1, 2, 2, 4), (1, 2, 3, 3), (1, 2, 3, 4), (1, 2, 4, 4), (1, 3, 3, 3), (1, 3, 3, 4), (1, 3, 4, 4), (1, 4, 4, 4), (2, 2, 2, 2), (2, 2, 2, 3), (2, 2, 2, 4), (2, 2, 3, 3), (2, 2, 3, 4), (2, 2, 4, 4), (2, 3, 3, 3), (2, 3, 3, 4), (2, 3, 4, 4), (2, 4, 4, 4), (3, 3, 3, 3), (3, 3, 3, 4), (3, 3, 4, 4), (3, 4, 4, 4), (4, 4, 4, 4)]
'''

댓글