Sum of adjacent subsequences in an array

Given the following array:

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

I want to calculate the sum of all possible sequences of size 4 as follows:

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

I applied a short python program to do this, and its inefficiency:

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 follows:

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

I notice that each element will participate in the summation operation 4 times, which is not very good. Do you have any effective idea? "I want to add that the size of the sequence is not fixed, in this example only 4. Thank you in advance

+4
source share
6 answers

Another approach would be to keep the cumulative amount to the current index and subtract the total total of 4,

tab = [80,12,14,5,70,9,26,30,8,12,16,15]
cumulative_sum = [0]*(len(tab)+1)
ret = []
for i in xrange(len(tab)):
    cumulative_sum[i+1] = cumulative_sum[i] + tab[i]
    if i >= 3:
      ret.append(cumulative_sum[i+1] - cumulative_sum[i-3])

( cumulativeSum tab)

tab = [0] + [80,12,14,5,70,9,26,30,8,12,16,15]
ret = []
for i in xrange(1, len(tab)):
    tab[i] += tab[i-1]
    if i >= 4:
      ret.append(tab[i] - tab[i-4])

, . , n, , cumulativeSum[index] - cumulativeSum[index-n]

+1
  • S1, 70 80, S2.
  • S2, 9 12, S3.
  • ...

, 4 .

+5

,

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]
+3

sum enumerate:

tab = [80,12,14,5,70,9,26,30,8,12,16,15]
sums = [sum(tab[i:i+4]) for i, v in enumerate(tab) if i+4 <= len(tab)]

print(sums)

:

[111, 101, 98, 110, 135, 73, 76, 66, 51]

4 , , 8,12,16,15 ( 51)

+2

, :

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

for i in range(len(tab) - 3):
    summation = sum(tab[i:i+4])
    print(summation)
+1

if you want to use numpy

A=np.array([80, 12, 14, 5, 70, 9, 26, 30, 8, 12, 16, 15])
print reduce(lambda x,y: x + [sum(y)], np.array(zip(A,A[1:],A[2:],A[3:])).tolist(),[])

conclusion

[111, 101, 98, 110, 135, 73, 76, 66, 51]

+1
source

Source: https://habr.com/ru/post/1669242/


All Articles