1.1前言:
本文将详细讲解itertools中的accumulate,accumulate函数可以在前缀和中运用,否则就需要每次移动的时候维护一个前缀和,大家如果不知道前缀和也可以先了解一下前缀和,前缀和可以解决数组区间和查询问题、矩阵区域和查询问题、连续子数组和问题、最大子段和问题、最大子矩阵和问题这里,但是如果大家不太了解前缀和也可以放心食用,因为运用这个累加函数其实十分简单。
1.2定义:
itertools. accumulate(iterable[,function,*,initial = None])
创建一个返回累积汇总值或来自其他双目运算函数的累积结果的迭代器。function 默认为加法运算。 function 应当接受两个参数,即一个累积汇总值和一个来自 iterable 的值。如果提供了 initial 值,将从该值开始累积并且输出将比输入可迭代对象多一个元素。
大家也可以自行实现前缀和,第一种是简易写法,这种写法其实已经满足很多前缀和的题目了,
pre_num = [0]
#由于为了满足前缀和的性质第一个数一定要置零才能满足所有的数都可以由两个前缀和来表示
for idx,x in enumerate(nums):
pre_num.append(pre_num[idx] + x)
accumulate大致相当于:
def accumulate(iterable, function=operator.add, *, initial=None):
'Return running totals'
# accumulate([1,2,3,4,5]) → 1 3 6 10 15
# accumulate([1,2,3,4,5], initial=100) → 100 101 103 106 110 115
# accumulate([1,2,3,4,5], operator.mul) → 1 2 6 24 120
iterator = iter(iterable)
total = initial
if initial is None:
try:
total = next(iterator)
except StopIteration:
return
yield total
for element in iterator:
total = function(total, element)
yield tot

最低0.47元/天 解锁文章
957

被折叠的 条评论
为什么被折叠?



