Перестановка и комбинация в Python
Python предоставляет прямые методы для поиска перестановок и комбинаций последовательности. Эти методы присутствуют в пакете itertools.
Перестановка
First import itertools package to implement the permutations method in python. This method takes a list as an input and returns an object list of tuples that contain all permutations in a list form.
Python3
# A Python program to print all # permutations using library function from itertools import permutations # Get all permutations of [1, 2, 3] perm = permutations([ 1 , 2 , 3 ]) # Print the obtained permutations for i in list (perm): print (i) |
Выход:
(1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1)
It generates n! permutations if the length of the input sequence is n.
If want want to get permutations of length L then implement it in this way.
Python3
# A Python program to print all # permutations of given length from itertools import permutations # Get all permutations of length 2 # and length 2 perm = permutations([ 1 , 2 , 3 ], 2 ) # Print the obtained permutations for i in list (perm): print (i) |
Выход:
(1, 2) (1, 3) (2, 1) (2, 3) (3, 1) (3, 2)
Он генерирует nCr * r! перестановки, если длина входной последовательности равна n, а входной параметр равен r.
Комбинация
This method takes a list and an input r as an input and return an object list of tuples which contain all possible combination of length r in a list form.
Python3
# A Python program to print all # combinations of given length from itertools import combinations # Get all combinations of [1, 2, 3] # and length 2 comb = combinations([ 1 , 2 , 3 ], 2 ) # Print the obtained combinations for i in list (comb): print (i) |
Выход:
(1, 2) (1, 3) (2, 3)
1. Combinations are emitted in lexicographic sort order of input. So, if the input list is sorted, the combination tuples will be produced in sorted order.
Python3
# A Python program to print all # combinations of a given length from itertools import combinations # Get all combinations of [1, 2, 3] # and length 2 comb = combinations([ 1 , 2 , 3 ], 2 ) # Print the obtained combinations for i in list (comb): print (i) |
Выход:
(1, 2) (1, 3) (2, 3)
2. Элементы считаются уникальными на основании их положения, а не их значения. Таким образом, если входные элементы уникальны, в каждой комбинации не будет повторяющихся значений.
Выход:
(2, 1) (2, 3) (1, 3)
3. If we want to make a combination of the same element to the same element then we use combinations_with_replacement.
Python3
# A Python program to print all combinations # with an element-to-itself combination is # also included from itertools import combinations_with_replacement # Get all combinations of [1, 2, 3] and length 2 comb = combinations_with_replacement([ 1 , 2 , 3 ], 2 ) # Print the obtained combinations for i in list (comb): print (i) |
Выход:
(1, 1) (1, 2) (1, 3) (2, 2) (2, 3) (3, 3)
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.