KatInterview

Mean Household Earnings with Gaps in the Data

Arrays & HashingAuto-graded · 23 test cases
EasyAuto-gradedArrays & Hashingarraysdata-cleaningnan-handling

Last updated

Compute the mean of a list of numbers while skipping None and NaN entries, returning 0.0 when nothing valid remains and rounding to two decimals.

Mean Household Earnings with Gaps in the Data

A survey produced a list of household earnings. Some entries are missing, and a missing entry appears either as None or as a floating-point NaN (float('nan')).

Write a function that returns the mean of the valid earnings.

Rules

  1. An entry is invalid if it is None or a floating-point NaN. Invalid entries are ignored completely, so they count neither toward the sum nor toward the number of entries.
  2. Every other entry is valid and must be included. This includes zero and negative numbers, since only None and NaN are excluded.
  3. If the list is empty or has no valid entries, return 0.0.
  4. Otherwise return the arithmetic mean of the valid entries, rounded to two decimal places (using Python's built-in round), as a float.

Input

  • earnings: a list whose elements are integers, floats, or None.

Output

  • A float: the rounded mean of the valid entries, or 0.0 when there are none.

Constraints

  • 0 <= len(earnings) <= 10^6
  • Each element is an int, a float (possibly NaN), or None.
  • The solution should run in linear time and should not need to build a filtered copy of the list.

Examples

Example 1

Input: mean_earnings([50000, None, 75000, 100000])

Output: 75000

Example 2

Input: mean_earnings([None])

Output: 0

Example 3

Input: mean_earnings([1, 2, 2])

Output: 1.67

Hints

Hint 1

NaN is never equal to anything, including itself, so `x == float('nan')` will not detect it. Look at `math.isnan`.

Hint 2

`math.isnan(None)` raises an error. Test for `None` first, and only call `isnan` on values that are floats.

Hint 3

You do not need to store the valid values. Keep a running total and a count, and check that the count is not zero before dividing.