Dada una lista, nuestra tarea es escribir un programa en Python para extraer todas las sublistas de longitud K que conduzcan a la suma dada.
Entrada: test_list = [6, 3, 12, 7, 4, 11], N = 21, K = 4
Salida: [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]
Explicación: se imprimen todos los grupos de longitud 4 y suma 21.
Entrada: test_list = [6, 3, 12, 7, 4, 11], N = 210, K = 4
Salida: []
Explicación: dado que la suma de ningún grupo de 4 tamaños es igual a 210, no se imprime ningún grupo como resultado.
Método: Usar sum() + producto() + bucle
En esto, todas las sublistas posibles de longitud K se calculan usando product(), sum() se usa para comparar la suma de la sublista con la suma requerida.
Python3
# Python3 code to demonstrate working of # K length groups with given summation # Using sum + product() from itertools import product # initializing list test_list = [6, 3, 12, 7, 4, 11] # printing original list print("The original list is : " + str(test_list)) # initializing Summation N = 21 # initializing size K = 4 # Looping for each product and comparing with required summation res = [] for sub in product(test_list, repeat = K): if sum(sub) == N: res.append(sub) # printing result print("The sublists with of given size and sum : " + str(res))
Producción:
La lista original es: [6, 3, 12, 7, 4, 11]
Las sublistas con tamaño y suma dados: [(6, 6, 6, 3), (6, 6, 3, 6), (6, 3, 6, 6), (6, 7, 4, 4), (6, 4, 7, 4), (6, 4, 4, 7), (3, 6, 6, 6), (3, 3, 3, 12), (3, 3, 12, 3), (3, 3, 4, 11), (3, 3, 11, 4), (3, 12, 3, 3), (3, 7, 7, 4), (3, 7, 4, 7), (3, 4, 3, 11), (3, 4, 7, 7), (3, 4, 11, 3), (3, 11, 3, 4), (3, 11, 4, 3), (12, 3, 3, 3), (7, 6, 4, 4), (7, 3, 7, 4), (7, 3, 4, 7), (7, 7, 3, 4), (7, 7, 4, 3), (7, 4, 6, 4), (7, 4, 3, 7), (7, 4, 7, 3), (7, 4, 4, 6), (4, 6, 7, 4), (4, 6, 4, 7), (4, 3, 3, 11), (4, 3, 7, 7), (4, 3, 11, 3), (4, 7, 6, 4), (4, 7, 3, 7), (4, 7, 7, 3), (4, 7, 4, 6), (4, 4, 6, 7), (4, 4, 7, 6), (4, 11, 3, 3), (11, 3, 3, 4), (11, 3, 4, 3), (11, 4, 3, 3)]
Publicación traducida automáticamente
Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA