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.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Hiring developers?
  1. Prepare
  2. Tutorials
  3. 10 Days of Statistics
  4. Day 7: Spearman's Rank Correlation Coefficient
  5. Discussions

Day 7: Spearman's Rank Correlation Coefficient

Problem
Submissions
Leaderboard
Discussions
Editorial
Tutorial

Sort 92 Discussions, By:

recency

Please Login in order to post a comment

  • lucasopoka
    4 months ago+ 0 comments
    n = int(input())
    a = list(map(float, input().split()))
    b = list(map(float, input().split()))
    ranks = lambda x : [sorted(x).index(i)+1 for i in x]
    spear = lambda n,a,b : 1-6*sum([(i[0]-i[1])**2 for i in list(zip(ranks(a),ranks(b)))]) / (n*(n**2-1))
    print(round(spear(n,a,b),3))
    
    0|
    Permalink
  • shashinp1996
    7 months ago+ 0 comments

    JavaScript

     function compareNumbers(a, b) {
            return a - b;
        }
        const data = input.split(/[\n]/g);
        const n = data[0],
        x = data[1].match(/\d+(?:\.\d+)?/g).map(Number),
        y= data[2].match(/\d+(?:\.\d+)?/g).map(Number);
        let sorted_x = [...x], sorted_y = [...y];
        sorted_x.sort(compareNumbers);
        sorted_y.sort(compareNumbers);
        let d = 0;
        for(let i = 0; i < n; i++) {
             d += Math.pow((sorted_x.indexOf(x[i]) - sorted_y.indexOf(y[i])), 2); 
        }
        let ans = 1 - ((6 * d) / (n * (Math.pow(n, 2) - 1)));
        console.log(ans.toFixed(3));  
    
    0|
    Permalink
  • lebaodai2611
    9 months ago+ 0 comments
    import sys
    from operator import itemgetter
    
    n = int(input())
    X = list(map(float, input().rstrip().split()))
    Y = list(map(float, input().rstrip().split()))
    N = [i+1 for i in range(n)]
    
    z = list(zip(X,Y))
    z_X = sorted(z, key=itemgetter(0)) 
    add_rx = dict(zip(z_X,N)) 
    z_Y = sorted(z, key=itemgetter(1)) 
    add_ry = dict(zip(z_Y,N))
    
    add_d_sq = {x:(add_rx.get(x,0)-add_ry.get(x, 0))**2 for x in set(add_rx).union(add_ry)}
    d_sq = list(add_d_sq.values())
    
    rxy = 1 - 6*sum(d_sq)/(n*(n**2-1))       
    print(round(rxy,3))             
    
    0|
    Permalink
  • abhishekjhingra1
    9 months ago+ 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)
    
    0|
    Permalink
  • sabsfilho
    9 months ago+ 0 comments

    c# version

        static void Main(String[] args) {
            System.Console.ReadLine();
            var xs = System.Console.ReadLine();
            var ys = System.Console.ReadLine();
            System.Console.WriteLine(
                SpearmanRank(ToArr(xs), ToArr(ys)).ToString("f3")
            );
        }
    
        static double[] ToArr(string xs)
        {
            var zs = xs.Trim().Split(' ');
            int l = zs.Length;
            var arr = new double[l];
            int i = -1;
            while(++i<l){
                arr[i] = double.Parse(zs[i]);
            }
            return arr;
        }
    
        static double SpearmanRank(double[] xs, double[] ys)
        {
            var rxs = GetRank(xs);
            var rys = GetRank(ys);
            
            int n = xs.Length;
            double r = 0;
            for(int i=0;i<n;i++)
            {
                r += Math.Pow(rxs[i] - rys[i], 2);
            }
            
            return 1.0 - (6 * r) / (n * ( Math.Pow(n, 2) - 1 ));
        }
    
        static double[] GetRank(double[] xs)
        {
            int n = xs.Length;
            var dic = new SortedDictionary<double, List<int>>();
            for(int i=0;i<n;i++)
            {
                var x = xs[i];
                List<int> ps;
                if (!dic.TryGetValue(x, out ps))
                {
                    ps = new List<int>();
                    dic.Add(x, ps);
                }
                ps.Add(i);
            }
            var rnks = new double[n];
            int p = 1;
            foreach(var d in dic)
            {
                var ws = d.Value;
                foreach(var w in ws)
                {
                    rnks[w] = p;
                }
                p++;
            }
            return rnks;
        }
    
    0|
    Permalink
Load more conversations

Need Help?


View tutorial
View editorial
View top submissions
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy