Home > Net >  Sum of products of 2 lists in python
Sum of products of 2 lists in python

Time:10-03

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 ideia is to take the mean of both of them

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

And them i calculate:

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

I'm kinda new in python, and I have no clue how to start the code, but maybe a for inside a for. Can anybody help me?

CodePudding user response:

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.

CodePudding user response:

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))

CodePudding user response:

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)

CodePudding user response:

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