medium +15 pts

Correlation Coefficient

Compute Pearson's r between two arrays.

Implement a function `correlation_coefficient(xs, ys)` that returns the Pearson correlation coefficient between two lists of numbers of equal length. The coefficient measures linear correlation and is defined as: r = sum((xi - mean(x)) * (yi - mean(y))) / sqrt(sum((xi - mean(x))^2) * sum((yi - mean(y))^2)) Return the result as a float. If the denominator is zero (i.e., either list has constant values or the lists are empty), return 0.0. The inputs will always be lists of ints or floats, and will have equal length. The function should not raise exceptions for valid inputs as described. Your function must be named exactly `correlation_coefficient` and accept two arguments `xs` and `ys` in that order.

Constraints

- The length of `xs` and `ys` is equal and non-negative. - Values can be any integers or floats, including negative numbers. - The time complexity should be O(n), where n is the length of the lists.

Example

>>> correlation_coefficient([1,2,3],[4,5,6])
1.0
>>> correlation_coefficient([1,2,3],[6,5,4])
-1.0
>>> correlation_coefficient([1,2,3],[2,4,6])
1.0
>>> correlation_coefficient([1,2,3],[1,2,3])
1.0
>>> correlation_coefficient([1,2,3],[3,1,2])
-0.5
>>> correlation_coefficient([1,2,3],[1,1,1])
0.0
15 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compute the means of both lists first.
Build the numerator and the two sum-of-squares terms using a single loop or two loops.
Check if either sum of squares is zero (or extremely close to zero) before dividing.
Use math.sqrt for the square root.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.