Reputation: 2503
writing a custom function Multiply the average of x,y
x=[17,13,12,15,16,14,16,16,18,19]
y=[94,73,59,80,93,85,66,79,77,91]
I have a two list and I want to calculate its average. After getting the two average I want to multiply
This code i have tried to achieve this functionality but not able to get the expected output. if any help appreciated
def X_bar_y_bar(x,y):
x1=[]
y1=[]
ab=[]
for i in x:
result_x1=i-sum(x)/float(len(x))
result_x1=result_x
x1.append(result_x1)
for k in y:
result_y1=k-sum(y)/float(len(y))
result_y1=result_y
y1.append(result_y1)
total=0
for i in x1:
for j in y1:
r1=i*j
total = +r1
print("{:.2f}".format(total))
Desired output:
20.02
17.42
74.52
-0.18
5.32
-5.48
-0.28
-6.48
38.42
Upvotes: 1
Views: 61
Reputation: 900
If you don't have to use 'numpy', then you can use the following code:
x=[17,13,12,15,16,14,16,16,18,19]
y=[94,73,59,80,93,85,66,79,77,91]
def X_bar_y_bar(x,y):
xave = sum(x)/float(len(x))
yave = sum(y)/float(len(y))
for i in range(len(x)):
result=((x[i]-xave)*(y[i]-yave))
print("{:.2f}".format(result))
X_bar_y_bar(x,y)
Few changes compared to your code:
1) the average is calculated once, you should bring it out of the loop 2) the assignment, 'result_x1=result_x', doesn't do anything, skip that
Upvotes: 1
Reputation: 36765
You should really use NumPy for things like these:
import numpy as np
x=np.array([17,13,12,15,16,14,16,16,18,19])
y=np.array([94,73,59,80,93,85,66,79,77,91])
(x - np.mean(x)) * (y - np.mean(y))
# array([20.02, 17.42, 74.52, -0.18, 5.32, -8.48, -5.48, -0.28, -6.48, 38.42])
Upvotes: 1