Katkat

Write an average-income function

MicrosoftData Scientist · Technical Screen

Last updated

This problem tests your ability to clean and aggregate numerical data using Python, specifically handling missing values (None/NaN) and calculating a clean arithmetic mean.

Problem Statement

Given a list of values representing household incomes, write a function calculate_average_income(incomes) that returns the average income.

Requirements:

  1. Ignore any entries that are None or NaN (represented as float('nan')).
  2. If the list is empty or contains only invalid values, the function should return 0.0.
  3. The result should be rounded to two decimal places.

Function Signature

def calculate_average_income(incomes: list) -> float:

Examples

Example 1: Input: [50000, None, 75000, 100000] Output: 75000.0 Explanation: The valid incomes are 50000, 75000, and 100000. The sum is 225000, divided by 3 equals 75000.0.

Example 2: Input: [None, float('nan')] Output: 0.0 Explanation: No valid numerical data exists, so return 0.0.

Edge Cases

  • Empty lists: []
  • Lists with only invalid values: [None, None]
  • Very large lists: Ensure your solution is efficient.

Hints

Hint 1

Use the `math.isnan()` function to check for floating-point NaN values.

Hint 2

Maintain two variables: a running sum of valid incomes and a count of valid entries encountered.

Hint 3

Remember to perform a check to avoid division by zero if the count of valid incomes is zero.

Follow-up questions

  • How would you modify this function to handle an extremely large list of incomes that does not fit into memory?
  • If the input data was stored in a Pandas Series instead of a list, how would the implementation change?
  • How would you update the function to return the median instead of the mean?