itsMe
itsMe

Reputation: 785

summing element in a range for all element in an array

I have to get the total sum of a range from an array. However the array range needs to move from one element to another. for example if the array is 1,2,3,4,5,6 and if every two element needs to be added , then it should add 1+2 than 2+3 than 3+4 and so on.

I have tried but not getting right approach. I am sure there is a pythonic way of doing this.

here what I have tried

data = np.arange(0,20,.3)
for i in range (0,len(data)):
    for j in range(i,len(data)):
        get_range = data[j:5]
        get_add = get_range.sum()
        print("sum:",get_add) 

I have tried to add every 5 element here.

Upvotes: 3

Views: 104

Answers (3)

koxy
koxy

Reputation: 123

There is a numpyic way to do this. It is more memory- and CPU- effective if your input data is big enougth.

import numpy as np

# input array: [1, 2, 3, 4, 5, 6]
data = np.arange(1, 7)

# cumulative sum: [1, 3, 6, 10, 15, 21]
data_cumsum = np.cumsum(data)

# append zero to start: [0, 1, 3, 6, 10, 15, 21]
data_cumsum = np.hstack([0, data_cumsum])

# calculate moving sum
window = 2
moving_sum = data_cumsum[window:] - data_cumsum[:-window]

print(moving_sum)

Output:

[ 3  5  7  9 11]

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

You could use a list comprehension which retrieves a chunks list.

l = [1,2,3,4,5,6]
n = 2
output = [sum(l[i:i + n]) for i in range(0, len(l) - n + 1, 1)]

Output

[3, 5, 7, 9, 11]

Upvotes: 3

mad_
mad_

Reputation: 8273

A minor change will solve the problem

data = np.arange(0,10)

for j in range(0,len(data)-1):
    get_range = data[j:j+2] #changed from j to j+2
    get_add = get_range.sum()
    print("sum:",get_add) 

OUTPUT

('sum:', 1)
('sum:', 3)
('sum:', 5)
('sum:', 7)
('sum:', 9)
('sum:', 11)
('sum:', 13)
('sum:', 15)
('sum:', 17)

You can easily condense above steps to form a list comprehension giving the same results with same complexity

[sum(data[j:j+2]) for j in range(0,len(data)-1)]

Another fancy approach could be using sliding_window function

from toolz.itertoolz import sliding_window
map(sum,list(sliding_window(2,list(range(0,10)))))

Output

[1, 3, 5, 7, 9, 11, 13, 15, 17]

Upvotes: 1

Related Questions