Python程序用给定的总和获得K个长度的组
给定一个列表,我们的任务是编写一个Python程序来提取所有 K 个长度的子列表,并得出给定的总和。
Input : test_list = [6, 3, 12, 7, 4, 11], N = 21, K = 4
Output : [(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)]
Explanation : All groups of length 4 and sum 21 are printed.
Input : test_list = [6, 3, 12, 7, 4, 11], N = 210, K = 4
Output : []
Explanation : Since no 4 size group sum equals 210, no group is printed as result.
方法:使用sum() + product() + loop
在这种情况下,所有可能的长度为 K 的子列表都使用 product() 计算,sum() 用于将子列表的总和与所需的总和进行比较。
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))
输出:
The original list is : [6, 3, 12, 7, 4, 11]
The sublists with of given size and sum : [(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)]