Day 7: Spearman's Rank Correlation Coefficient

  • + 0 comments
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    import statistics as stat
    from sys import stdin, stdout
    
    def spearman(X, Y, n):
        def rank(arr):
            ref = sorted(arr)
            rank = []
            for ele in arr:
                rank.append(ref.index(ele)+1)
            return rank
        
        def correlation(X, Y, n):
            std_x = stat.pstdev(X)
            std_y = stat.pstdev(Y)
            m_x = stat.mean(X)
            m_y = stat.mean(Y)
            corr = 0
            for i in range(n):
                corr += (X[i]-m_x)*(Y[i]-m_y)/n
            p_coeff = corr/(std_x*std_y)
            return round(p_coeff, 3)
        
        rank_x = rank(X)
        rank_y = rank(Y)
        spearman_coeff = correlation(rank_x, rank_y, n)
        stdout.write(str(spearman_coeff))
                    
        
    n = int(stdin.readline().strip())
    X = list(map(float, stdin.readline().strip().split()))
    Y = list(map(float, stdin.readline().strip().split()))
    spearman(X, Y, n)