使用累加功能在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]