NiRvanA
NiRvanA

Reputation: 135

Cumsum returning a vector in python

I have my array, say: [10, 6, 4, 12]. I am interested in finding a vector of cumulative sums, i.e.: [10, 16, 20, 32]. Obvious approach would be to use a for loop:

r = []
for ind in range(4):
  r.append(s[ind])  # s is [10, 6, 4, 12]
r = cumsum(r)

However, this seems really inefficient. I want to ask if there is a pre-defined function or I should specify specific arguments in cumsum.

Upvotes: 0

Views: 164

Answers (2)

Alderven
Alderven

Reputation: 8270

Libless solution:

s = [10, 6, 4, 12]
r = [sum(s[:i+1]) for i in range(len(s))]

Output:

[10, 16, 20, 32]

Upvotes: 0

Chetan Ameta
Chetan Ameta

Reputation: 7896

there are many ways like np.cumsum or python 3.2+ you can use itertools.accumulate

By Itertool:

l = [10, 6, 4, 12]

from itertools import accumulate

print(list(accumulate(l)))

output:

[10, 16, 20, 32]

Using numpy:

import numpy as np

print(np.cumsum(l))

output:

[10, 16, 20, 32]

Upvotes: 1

Related Questions