Iterative summation

Viewed 475

I'm trying to write a python code that allows me to iteratively sum up the average values of three elements of a list, starting with the third element and its two predecessors. Let me give you an example:

list = [1, 2, 3, 4, 5, 6, 7]

I want to calculate the following:

sum_of_average_values = sum(1, 2, 3)/3 + sum(2, 3, 4)/3 + sum(3, 4, 5)/3 + sum(4, 5, 6)/3 + sum(5, 6, 7)/3 

Since I'm quite new to programming I couldn't find an effective way of putting this into a function.

6 Answers

You can do in this way:

a = [1,2,3,4,5,6,7]
sum_of_average_values = 0
for i in range(0,len(a)-2):
    sum_of_average_values += sum(a[i:i+2])/3
print(sum_of_average_values)

Many ways to achieve this, one way is recursively. The function averages the last three elements of a list and adds the result to the result generated by the function with a list lacking the last element. Continues like this until the list is shorter than 3.

def fn(l):
    if len(l) < 3: 
        return 0
    return sum(l[-3:])/3 + fn(l[:-1])

print(fn([1, 2, 3, 4, 5, 6, 7]))

Another solution where you can specify the amount of elements you want to sum up and average:

l = [1, 2, 3, 4, 5, 6, 7]

def sum_avg(l, n):
  res = 0
  for i in range(n-1, len(l)):
    res += sum([l[j] for j in range(i, i-n, -1)])/n
    
  return res

print(sum_avg(l, 3))

--> 20.0

You could use rolling from pandas.

import pandas as pd

num_list = [1, 2, 3, 4, 5, 6, 7]

average_sum = sum(pd.Series(num_list).rolling(3).mean().dropna())

print(average_sum)

Mathematically, this would could be obtain by averaging the sums of 3 sublists:

L = [1, 2, 3, 4, 5, 6, 7]  

r = (sum(L) + sum(L[1:-1]) + sum(L[2:-2]))/3  # 20.0

and can be generalized to a window size of w:

w = 3
r = sum(sum(L[p:-p or None]) for p in range(w)) / w

It can also be implemented without the overhead of generating sublists by using item positions to determine the number of times they are added to the total:

r = sum(n*min(i+1,len(L)-i,w) for i,n in enumerate(L)) / w

This would be the most memory-efficient of the 3 methods because it use an iterator to feed data to the sum function and only goes through the data once.

Detailed explanation:

  • Since all the averages that are added together are a division by 3, we can produce the total sum and divide by 3 at the end
  • the number at the first and last positions are added once
  • the number at the second and penultimate positions are added twice
  • The numbers from the third position up to the antepenultimate will be added 3 times

visually:

(1   + 2   + 3)                             / 3
      (2   + 3   + 4)                       / 3
            (3   + 4   + 5)                 / 3
                  (4   + 5   + 6)           / 3
                        (5   + 6   + 7)     / 3

(1x1 + 2x2 + 3x3 + 4x3 + 5x3 + 6x2 + 7x1)   / 3 = 20.0

 n =  1   2   3   4   5   6   7   # value
 * =  1   2   3   3   3   2   1   # multiplier (times added)
      -------------------------
     (2,  4,  9, 12, 15, 12,  7) / 3 = 20.0

 i =  0   1   2   3   4   5   6   # index
      1   2   3   3   3   2   1   # min(i+1,len(L)-i,w) = multiplier

You can do in one line using list comprehension as:

n = 3
avg = sum( [ sum(lst[i:i+n])/n for i in range(0, len(lst) - (n - 1)) ] )
print(avg) # 20.0
Related