내장모듈 - itertools(순열, 조합, 프로덕트, 중복순열)

oneofakindscene·2021년 8월 7일
0

python

목록 보기
5/7
  • itertools에서 계산하는 값들은 list를 씌워야 핸들링하기 쉽다

프로덕트(product)

  • product(string1, string2) 이렇게 주어지면 => len(string1) * len(string2) 만큼의 조합 갯수가 나옴
    • 동일한 예로 product(list1, list2) 이렇게 주어지면 => len(list1) * len(list2) 만큼의 조합 갯수가 나옴
  • product(list, repeat=n) 이렇게 주어지면 => len(list1)^n 만큼의 조합 갯수가 나옴
    • repeat=3은 각 element를 최대 몇개까지 쓸 수 있는지를 알려준다고 생각하자.
    • [0,1] 이면 => (0,0,0), (1,1,1)이 뽑힐 수 있다는 뜻
>>> from itertools import prodouct
>>> list(product('ABCD', 'xy')) 
[('A', 'x'), ('A', 'y'), ('B', 'x'), ('B', 'y'), ('C', 'x'), ('C', 'y'), ('D', 'x'), ('D', 'y')]
>>> list(product([0,1], repeat=3))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

순열과 조합

  • 순열 : 순서가 바뀌면 다른 조합이다.
    • (1,2,3) => 2개로 뽑아서 순열만들면 => (1,2), (2,1), (1,3), (3,1)
  • 조합 : 순서가 바뀌어도 (element가 같으면) 같은 조합이다.

순열(permutations)

  • permutations(list, r) 형태로 사용
    • r은 list에서 몇개 뽑을거냐를 의미함, product에서 쓰이는 repeat과 헷갈리지 말 것
>>> from itertools import permutations
>>> list(permutations([1,2,3], 2))
[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

# 정렬안된 list로 combinations하면 정렬안된 순서로 조합 결과가 나오는 것을 알 수 있음
>>> list(permutations([3,1,2], 2))
[(3, 1), (3, 3), (1, 3), (1, 3), (3, 3), (3, 1)]

조합(combinations)

  • combinations(list, r) 형태로 사용
    • r은 list에서 몇개 뽑을거냐를 의미함, product에서 쓰이는 repeat과 헷갈리지 말 것
  • (tip) 2개의 조합을 뽑을때, list를 정렬시킨 상태에서 combinations를 하면 combination 결과로 나오는 tuple에서 첫번째 element가 두번째 element보다 작은수가 나오게 된다
>>> from itertools import combinations
>>> list(combinations([1,2,3], 2))
[(1, 2), (1, 3), (2, 3)]

# 정렬안된 list로 combinations하면 정렬안된 순서로 조합 결과가 나오는 것을 알 수 있음
>>> list(combinations([3,1,2], 2))
[(3, 1), (3, 2), (1, 2)]

중복순열(combinations_with_replacement)

  • 조합(combinations)의 성질인 element 순서가 바뀌어도 같다라는 성질은 유지한 상태로 중복을 허용해서 조합들을 만듦
>>> from itertools import combinations_with_replacement
>>> print(list(combinations_with_replacement([1,2,3], 3)))
[(1, 1, 1), (1, 1, 2), (1, 1, 3), (1, 2, 2), (1, 2, 3), (1, 3, 3), (2, 2, 2), (2, 2, 3), (2, 3, 3), (3, 3, 3)]
>>> print(list(combinations_with_replacement([3,1,3], 3)))
[(3, 3, 3), (3, 3, 1), (3, 3, 3), (3, 1, 1), (3, 1, 3), (3, 3, 3), (1, 1, 1), (1, 1, 3), (1, 3, 3), (3, 3, 3)]

프로덕트 vs 중복순열

  • 프로덕트 : 중복이 허용 & element 순서가 바뀌면 다른 케이스로 인식
  • 중복순열 : 중복이 허용 & element 순서가 바뀌어도 같은 케이스로 인식
  • 프로덕트로 나오는 튜플값들에 set()을 씌우면 => 중복순열로 나오는 값과 같음
>>> print(list(product([1,2], repeat=2)))
[(1, 1), (1, 2), (2, 1), (2, 2)]
>>> print(list(combinations_with_replacement([1,2], 2)))
[(1, 1), (1, 2), (2, 2)]

References

profile
oneofakindscene

0개의 댓글