Sum of products of two lists

Viewed 80

I'm trying to create a function that can calculate the sum of products in Python.

I have two lists:

x1 = [3, 1, 3, 1, 3, 13]
x2 = [2, 3, 31, 3, 13, 3]

My idea is to take the mean of both of them:

m1 = mean(x1)
m2 = mean(x2)

And then calculate:

(x1[0] - m1) * (x2[0] - m2)+(x1[1] - m1) * (x2[1] - m2)+(x1[2] - m1)*(x2[2] - m2)... until the end of both of the lists.

4 Answers

The key is to use zip to combine the lists in pairs:

sumprod = sum(a*b for a,b in zip(x1,x2))

Not sure what you're doing with the "means" there.

You can use a single for loop.

import statistics

x1 = [3,1,3,1,3,13]
x2 = [2,3,31,3,13,3]

m1 = statistics.mean(x1)
m2 = statistics.mean(x2)

n = len(x1) # assuming x1 and x2 will always be the same length
res = 0 # this will store the final ans

# here i will be 0, 1, 2, ... n
for i in range(n):
    res += ((x1[i] - m1) * (x2[i] - m2))

print(res)

Tim Roberts solution works if you are trying to do what your title says, but your explanation is slightly different. Perhaps his answer combined with mine will get you started in the right direction. I wrote a function, then took both lists you provided and multiplied them:

def avgdiff(mylist):
    listavg=sum(mylist)/len(mylist)
    outval=1
    for x in mylist:
        outval=outval*abs(x-listavg)
    return outval


x1 = [3,1,3,1,3,13]
x2 = [2,3,31,3,13,3]

print(avgdiff(x1)*avgdiff(x2))

It is possible in one loop in many ways. Here I tried to make the code clean

x1 = [3, 1, 3, 1, 3, 13]
x2 = [2, 3, 31, 3, 13, 3]

m1 = sum(x1) / len(x1)  # the mean of x1
m2 = sum(x2) / len(x2)  # the mean of x2

ans = 0

for num1, num2 in zip(x1, x2):
    ans += ((num1 - m1) * (num2 - m2))

ans is the answer.

Related