📜  Python|每个 K 值的分块求和

📅  最后修改于: 2022-05-13 01:55:41.875000             🧑  作者: Mango

Python|每个 K 值的分块求和

前缀数组在编程界非常有名。本文将讨论该方案的一种变体。这处理累积列表总和直到 K 值,并再次从 K 值的出现开始累积总和。让我们讨论一下可以执行此操作的特定方式。

方法#1:使用朴素方法
在朴素的方法中,我们只是构造了由 prev 之和组成的新列表。 list 的值直到 K 并在遇到非 K 值时重新启动该过程。

# Python3 code to demonstrate 
# Chuncked summation every K value
# using naive method 
  
# initializing list of lists
test_list = [1, 3, 4, 10, 4, 5, 10, 7, 8]
  
# printing original list
print ("The original list is : " + str(test_list))
  
# initializing K 
K = 10
  
# Chuncked summation every K value
# using naive method
for i in range(1, len(test_list)):
    if test_list[i]: 
        test_list[i] += test_list[i - 1]
    else:
        test_list[i] = 0
  
# printing result
print ("The computed modified new list : " + str(test_list))
输出 :
The original list is : [1, 3, 4, 10, 4, 5, 10, 7, 8]
The computed modified new list : [1, 4, 8, 18, 22, 27, 37, 44, 52]