time_interval = [4, 6, 12]
I want to sum up the numbers like [4, 4+6, 4+6+12]
in order to get the list t = [4, 10, 22]
.
I tried the following:
for i in time_interval:
t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)
4 10 22
4 10 22
4 10 22
Somewhat hacky, but seems to work:
I did think that the inner function would be able to modify the
y
declared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.First, you want a running list of subsequences:
Then you just call
sum
on each subsequence:(This isn't the most efficient way to do it, because you're adding all of the prefixes repeatedly. But that probably won't matter for most use cases, and it's easier to understand if you don't have to think of the running totals.)
If you're using Python 3.2 or newer, you can use
itertools.accumulate
to do it for you:And if you're using 3.1 or earlier, you can just copy the "equivalent to" source straight out of the docs (except for changing
next(it)
toit.next()
for 2.5 and earlier).A pure python oneliner for cumulative sum:
This is a recursive version inspired by recursive cumulative sums. Some explanations:
X[:1]
is a list containing the previous element and is almost the same as[X[0]]
(which would complain for empty lists).cumsum
call in the second term processes the current element[1]
and remaining list whose length will be reduced by one.if X[1:]
is shorter forif len(X)>1
.Test:
And simular for cumulative product:
Test:
In Python 2 you can define your own generator function like this:
And in Python 3.2+ you can use
itertools.accumulate()
:Behold:
Will output (as expected):