개발/Python

[Python] - Permutation & Combination

Dortmoot 2022. 7. 27. 19:50

Permutation

  • process of changing the linear order of an ordered set
  • support itertools
  • Permutations differ from combinations , which are selections of some members of a set regardless of order
  • set {1, 2, 3} -> (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)

 

Syntax

permutations(iterable, r=None)
from itertools import permutations

list( permutations('ABC', 2) )
> [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]

permutations(range(3))
> [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]

 

Combination

  • a combination is a selection of items from a set that has distinct members, such that the order of selection does not matter
  • support itertools
  • set {1, 2, 3} -> (1,2),(1,3),(2,3)

Syntax

combinations(iterable, r)
from itertools import combinations

list(combinations('ABCD', 2))
> [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'C'), ('B', 'D'), ('C', 'D')]

list(combinations(range(4), 3))
> [(0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3)]

 

Combinations_with_replacement

  • like a combinations but this case available copy data
  • set {1,2,3} -> (1,1), (1,2), (1,3), (2,1), (2,2),(2,3),(3,3)
from itertools import combinations_with_replacement

combinations_with_replacement(range(5),2)