We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
# import statistics as statfromsysimportstdin,stdoutimportmathdefmean(arr):returnsum(arr)/len(arr)defsd(arr,mean):squared_diff_sum=sum((x-mean)**2forxinarr)variance=squared_diff_sum/len(arr)returnmath.sqrt(variance)defcovariance(X,Y):mean_X=mean(X)mean_Y=mean(Y)covariance_sum=sum((X[i]-mean_X)*(Y[i]-mean_Y)foriinrange(len(X)))cov=covariance_sum/len(X)returncovdefpearson_correlation(X,Y):cov_XY=covariance(X,Y)st_dev_X=sd(X,mean(X))st_dev_Y=sd(Y,mean(Y))coefficient=cov_XY/(st_dev_X*st_dev_Y)returncoefficientn=int(stdin.readline().strip())X=list(map(float,stdin.readline().strip().split()))Y=list(map(float,stdin.readline().strip().split()))iflen(X)!=len(Y):print("Error: Data sets X and Y must have equal lengths")else:t=pearson_correlation(X,Y)print(round(t,3))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 7: Pearson Correlation Coefficient I
You are viewing a single comment's thread. Return to all comments →
Easy Solution: