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
for x in list(permutations(tab, 4)):print (sum(x))