• + 0 comments

    Easy Solution:

    # import statistics as stat
    from sys import stdin, stdout
    import math
    
    def mean(arr):
        return sum(arr) / len(arr)
    
    def sd(arr, mean):
        squared_diff_sum = sum((x - mean)**2 for x in arr)
        variance = squared_diff_sum / len(arr)
        return math.sqrt(variance)
    
    def covariance(X, Y):
        mean_X = mean(X)
        mean_Y = mean(Y)
        covariance_sum = sum((X[i] - mean_X) * (Y[i] - mean_Y) for i in range(len(X)))
        cov = covariance_sum / len(X)
        return cov
    
    def pearson_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)
        return coefficient
    
    n = int(stdin.readline().strip())
    X = list(map(float, stdin.readline().strip().split()))
    Y = list(map(float, stdin.readline().strip().split()))
    
    if len(X) != len(Y):
        print("Error: Data sets X and Y must have equal lengths")
    else:
        t = pearson_correlation(X, Y)
        print(round(t, 3))