Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of contigous subsequences in an array

Given the following array:

tab = [80,12,14,5,70,9,26,30,8,12,16,15]

I want to compute the sum of all possible sequences of size 4 as follow:

S1=80+12+14+5=111
S2=12+14+5+70 =101
S3=14+5+70+9 =98
....

I have implmented a short program on python to do this and its not efficient:

import numpy as np


tab= np.array([80,12,14,5,70,9,26,30,8,12,16,15])
tab_size=tab.size
n=tab_size
s=0
seq_len=5
for i in range (0,n-(seq_len-1),1):
    print("index i ",i)
    for k in range(i+1,(seq_len+i),1):
            print ("index k ", k)
            tab[i]=tab[i]+tab[k]
            s=s+1
print(s)         
tab

the result is as follow :

array([111, 101,  98, 110, 135,  73,  76,  66,  51,  12,  16,  15])

I notice that each element will participate in the sum operation 4 times which is not good. do you have any efficient idea to do that?
I want to add that, the sequence size is not fixed, in this example is just 4. Thank you in advance

like image 274
alae Avatar asked Dec 11 '22 12:12

alae


2 Answers

  • Once you calculated S1, you just need to add 70 and substract 80 to get S2.
  • Once you calculated S2, you just need to add 9 and substract 12 to get S3.
  • ...

This way, you'll avoid using each element 4 times.

like image 159
Eric Duminil Avatar answered Dec 13 '22 12:12

Eric Duminil


Try this,

print [sum(item) for item in [tab[n:n+4] for n in range(0, len(tab))] if len(item) == 4]
# Result [111, 101, 98, 110, 135, 73, 76, 66, 51]
like image 20
Rahul K P Avatar answered Dec 13 '22 11:12

Rahul K P