Compute Spearman rank correlation with averaged tie ranks

Does a cheap judge rank answers the same way as humans? Spearman correlation compares ranks, not raw scores, so it is robust to different scales.

Write spearman(x, y) for two 1D arrays of the same length. Rank each array from 1 to n, giving tied values the average of the ranks they span. Return the Pearson correlation of the two rank arrays. If either rank array is constant, return 0.0.

Signaturedef spearman(x, y)

Example

spearman([1, 2, 2, 3], [10, 20, 20, 40]) is 1.0.

Understand the idea

Spearman correlation asks whether two lists rank items the same way, ignoring the actual score scales. Replace each value by its rank, then take the ordinary Pearson correlation of the ranks. Tied values share the average of the ranks they cover, which keeps the total rank sum fixed. Worked example: x = [10, 20, 20, 30], y = [1, 3, 2, 4]. Ranks of x: 10 is 1, the two 20s cover ranks 2 and 3, so each gets 2.5, and 30 is 4: [1, 2.5, 2.5, 4]. Ranks of y: [1, 3, 2, 4]. Both have mean 2.5. Deviations: x [-1.5, 0, 0, 1.5], y [-1.5, 0.5, -0.5, 1.5]. Sum of products = 2.25 + 0 + 0 + 2.25 = 4.5. Sums of squares 4.5 and 5. r = 4.5 / sqrt(4.5 * 5) = 0.9487. Rule: average ranks for ties, Pearson correlation of the rank arrays, and return 0.0 if either rank array is constant. Giving all tied values the first rank biases the result. Used to check whether a cheap LLM judge orders answers the way human raters do.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplespearman([1, 2, 2, 3], [10, 20, 20, 40])
  • Sample 2: reversedspearman([1, 2, 3, 4], [9, 7, 5, 1])
  • Test 3: ties on one sidespearman([1, 1, 2, 3, 3], [2, 1, 4, 3, 5])
  • Test 4: constantspearman([1, 1, 1], [1, 2, 3])