#436Spearman Rank CorrelationEasy

Spearman Rank Correlation

Background

Spearman's rho is Pearson's correlation applied to ranks instead of raw values. It captures monotonic relationships and is the canonical calibration target for LLM-as-judge against human gold sets (production target ρ>0.8\rho > 0.8).

Problem statement

Implement spearman_corr(x, y). Replace each value by its 1-indexed rank (averaging ranks for ties), then apply Pearson:

ρ  =  i(RixRˉx)(RiyRˉy)i(RixRˉx)2i(RiyRˉy)2\rho \;=\; \frac{\sum_i (R_i^x - \bar{R}^x)(R_i^y - \bar{R}^y)}{\sqrt{\sum_i (R_i^x - \bar{R}^x)^2}\,\sqrt{\sum_i (R_i^y - \bar{R}^y)^2}}

Input

  • x, y - array-like of floats, same length 2\ge 2.

Output

  • float in [1,1][-1, 1].

Examples

Input: x=[1,2,3,4,5], y=[2,4,6,8,10]
Output: 1.0       # perfectly monotonic
Input: x=[1,2,3,4,5], y=[5,4,3,2,1]
Output: -1.0

Constraints

  • Use average ranks for ties (the standard convention).
  • Lengths must match and be 2\ge 2. Raise ValueError otherwise.

Notes

  • vs Pearson. Pearson is sensitive to outliers; Spearman is robust because it only uses ranks. Use Spearman whenever the relationship is monotonic but not linear.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Reference example perfectly increasing gives one
  • Example perfectly decreasing gives minus one
  • Sample with ties averaged gives one