Python 中使用 accumulate 函数建立前缀和数组
给定一个数组,我们必须使用 accumulate 函数制作前缀和数组。itertools.accumulate(iterable[, func]) 模块函数全部构造并返回迭代器。因此,它们仅应该通过截断流的函数或循环访问。生成返回累加总和的迭代器。元素可以是任何可加类型,包括 Decimal 或 Fraction。如果提供了可选函数参数,它应该是两个参数的函数,它将被用作加法运算。
示例
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]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP