Join Our 5-Week ML/AI Engineer Interview Bootcamp 🚀 led by ML Tech Leads at FAANGs

Back to Questions

3. Pearson Correlation

medium
GoogleGoogle
entry

Given two arrays of numbers representing paired observations, compute the Pearson correlation coefficient rr between them using NumPy.

Return the correlation coefficient rounded to 2 decimal places.

Input Signature
ArgumentType
nums1list
nums2list
Output Signature
Return NameType
valuefloat

Constraints

  • len(nums1) == len(nums2); otherwise must raise ValueError.

  • n = len(nums1) >= 2; otherwise must raise ValueError.

  • Inputs must be Python list objects; otherwise must raise TypeError.

  • If either list has zero variance (denominator is 0), must raise ValueError (correlation undefined).

Hint 1

Compute the means xˉ\bar{x} and yˉ\bar{y} first, then iterate again to accumulate numerator and denominator terms.

Hint 2

The denominator is ∑dx2⋅∑dy2\sqrt{\sum dx^2 \cdot \sum dy^2}; if it becomes 0, correlation is undefined.

Hint 3

Use round(r, 2) at the end to enforce 2-decimal output.

Roles
Data Scientist
Companies
GoogleGoogle
Levels
entry
Tags
numpy
22 people are solving this problem
Python LogoPython Editor
Ln 1, Col 1

Input Arguments

Edit values below to test with custom inputs

You need tolog in/sign upto run or submit