使用累加功能在python中添加前缀sum数组
给定一个数组,我们必须使用function.itertools.accumulate(iterable[,func])模块函数来构造所有前缀并返回迭代器。因此,它们只能由截断流的函数或循环访问。进行迭代,以返回累加的总和。元素可以是任何可加类型,包括小数或小数。如果提供了可选的函数参数,则它应该是两个参数的函数,并且将使用它代替加法。
示例
Input: Data = [1, 0, 2, 3, 5] >>> list(accumulate(data)) # running summation Output: [1, 1, 3, 6, 11]
算法
Step 1: Create list. Step 2: Use list(accumulate( ))) function, its return running total. Step 3: Display total.
范例程式码
# Python program to print prefix
#sum array using accumulate function
from itertools import accumulate
def summation(A):
print ("The List after Summation ::>", list(accumulate(A)))
# Driver program
if __name__ == "__main__":
A=list()
n=int(input("Enter the size of the First List ::"))
print("Enter the Element of First List ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
summation(A)输出结果
Enter the size of the First List ::5 Enter the Element of First List :: 1 2 3 4 5 The List after Summation ::> [1, 3, 6, 10, 15]
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下