26.6k views
0 votes
Need to use Python to create the below function;

''' This function takes as input two lists of same length. It outputs net correlation value between these two lists. To compute correlation between two lists:
1. Compute the average of each list
2. Subtract a list's average from every element in the list (repeat for both lists)
3. Multiply corresponding differences from each list to compute the element-wise correlation
4. Sum all the values from step 3 to compute the net correlation value
Example: [-10,0,10,20],[20,10,10,20] -> 0
def compute_net_correlation(self,data_series_1,data_series_2):
''' #### FILL IN CODE HERE ####
net_correlation = # fill in computation
return net_correlation

User Seltsam
by
5.0k points

1 Answer

6 votes

Answer:

The function is as follows:

def compute_net_correlation(data_series_1,data_series_2):

series1 = 0; series2 = 0

for i in range(len(data_series_1)):

series1+=data_series_1[i]

series2+=data_series_2[i]

avg_series1 =series1/len(data_series_1)

avg_series2 =series2/len(data_series_1)

for i in range(len(data_series_1)):

data_series_1[i]-=avg_series1

data_series_2[i]-=avg_series2

data_series_1[i]*=data_series_2[i]

net_correlation = 0

for i in range(len(data_series_1)):

net_correlation +=data_series_1[i]

return net_correlation

Step-by-step explanation:

This defines the function

def compute_net_correlation(data_series_1,data_series_2):

This initializes the sum of each series to 0

series1 = 0; series2 = 0

This iterates through each data series

for i in range(len(data_series_1)):

This adds series 1

series1+=data_series_1[i]

This adds series s

series2+=data_series_2[i]

This calculates the average of data series 1

avg_series1 =series1/len(data_series_1)

This calculates the average of data series 2

avg_series2 =series2/len(data_series_1)

This iterates through each data series

for i in range(len(data_series_1)):

This subtracts the average from series 1

data_series_1[i]-=avg_series1

This subtracts the average from series 2

data_series_2[i]-=avg_series2

This multiplies the corresponding elements of both series

data_series_1[i]*=data_series_2[i]

This initializes the net correlation to 0

net_correlation = 0

This iterates through each data series

for i in range(len(data_series_1)):

This adds up the corresponding elements of both series

net_correlation +=data_series_1[i]

This returns the net correlation

return net_correlation

User Maiermic
by
5.0k points