Python程序查找组和直到列表中的每个 K
给定一个列表,任务是编写一个Python程序来执行总和的分组,直到出现 K。
例子:
Input : test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1], K = 6
Output : [10, 6, 2, 6, 21, 6, 1]
Explanation : 2 + 3 + 5 = 10, grouped and cummulated before 6.
Input : test_list = [2, 3, 5, 6, 2, 6, 8], K = 6
Output : [10, 6, 2, 6, 8]
Explanation : 2 + 3 + 5 = 10, grouped and cummulated before 6.
方法:使用循环
在这里,我们维护一个求和计数器,如果 K 发生,求和将与 K 一起附加到结果列表中,否则求和计数器用当前值更新。
Python3
# Python3 code to demonstrate working of
# Group Sum till each K
# Using loop
from collections import defaultdict
# initializing list
test_list = [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1]
# printing original lists
print("The original list is : " + str(test_list))
# initializing K
K = 6
temp_sum = 0
res = []
for ele in test_list:
if ele != K:
temp_sum += ele
# append and re initializing if K occurs
else:
res.append(temp_sum)
res.append(ele)
temp_sum = 0
res.append(temp_sum)
# printing result
print("Computed list : " + str(res))
输出
The original list is : [2, 3, 5, 6, 2, 6, 8, 9, 4, 6, 1]
Computed list : [10, 6, 2, 6, 21, 6, 1]