All problems
Theil-Sen Slope
Problem
Compute the Theil-Sen slope: the median of all pairwise slopes (y_j - y_i) / (x_j - x_i) for i < j with distinct x values (average the two middle slopes for an even count).
Return 0.0 when no valid pair exists.
Hint
The median of pairwise slopes is robust to outliers, unlike ordinary least squares.
Test cases
case 1
in: [[1,2,3],[2,4,6]]
expected: 2
case 2
in: [[1,2,3,4],[1,2,10,4]]
expected: 1
case 3
in: [[1,1,2],[1,2,3]]
expected: 1.5
case 4
in: [[5],[3]]
expected: 0
Starter codePython
def theil_sen_slope(X, y):
# Your code here
pass4 test cases · run your code against them in the editor