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
S1, you just need to add 70 and substract 80 to get S2.S2, you just need to add 9 and substract 12 to get S3.This way, you'll avoid using each element 4 times.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With