Day 7: Spearman's Rank Correlation Coefficient

  • + 0 comments

    Python 3 solution without external libraries:

    n = int(input())
    X = list(map(float, input().split()))
    x = sorted(X)
    Y = list(map(float, input().split()))
    y = sorted(Y)
    
    x_enumeration = {val: rank + 1 for rank, val in enumerate(x)}  # Map values to ranks
    X_ranks = [x_enumeration[val] for val in X]  # Generate ranks for the original list
    
    y_enumeration = {val: rank + 1 for rank, val in enumerate(y)}  # Map values to ranks
    Y_ranks = [y_enumeration[val] for val in Y]  # Generate ranks for the original list
    
    rho = 1 - (6 * sum((X_rank - Y_rank)** 2 for X_rank, Y_rank in zip(X_ranks, Y_ranks)) / (n * (n**2 - 1)))
    
    print(round(rho, 3))