Python proporciona métodos directos para encontrar permutaciones y combinaciones de una secuencia. Estos métodos están presentes en el paquete itertools.
Permutación
Primero importe el paquete itertools para implementar el método de permutaciones en python. Este método toma una lista como entrada y devuelve una lista de objetos de tuplas que contienen todas las permutaciones en forma de lista.
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)
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)
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)
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)
Python3
# A Python program to print all combinations # of given length with unsorted input. from itertools import combinations # Get all combinations of [2, 1, 3] # and length 2 comb = combinations([2, 1, 3], 2) # Print the obtained combinations for i in list(comb): print (i)
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)
Publicación traducida automáticamente
Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA