Mean Household Earnings with Gaps in the Data
Arrays & HashingAuto-graded · 23 test casesLast 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
- An entry is invalid if it is
Noneor a floating-point NaN. Invalid entries are ignored completely, so they count neither toward the sum nor toward the number of entries. - Every other entry is valid and must be included. This includes zero and negative numbers, since only
Noneand NaN are excluded. - If the list is empty or has no valid entries, return
0.0. - Otherwise return the arithmetic mean of the valid entries, rounded to two decimal places (using Python's built-in
round), as afloat.
Input
earnings: a list whose elements are integers, floats, orNone.
Output
- A
float: the rounded mean of the valid entries, or0.0when there are none.
Constraints
0 <= len(earnings) <= 10^6- Each element is an
int, afloat(possibly NaN), orNone. - 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Walk through the list once, keeping two running values: total, the sum of valid entries, and count, how many valid entries have been seen.
For each element:
- If it is
None, skip it. - If it is a
floatandmath.isnanis true for it, skip it. - Otherwise add it to
totaland incrementcount.
After the loop, if count is zero, return 0.0. Otherwise return total / count rounded to two decimals as a float.
Why it works
- Each valid entry is added to the total and counted exactly once, so
total / countis the arithmetic mean of the valid entries. - Invalid entries are skipped before they touch either accumulator. This matters for NaN in particular, because a single NaN added to a sum would make the whole result NaN.
- The
Nonecheck comes first, somath.isnanis never called onNone(which would raise aTypeError). Theisinstance(..., float)guard meansisnanonly runs on floats; integers can never be NaN. - NaN cannot be found with
==, since it compares unequal to everything including itself, which is whymath.isnanis used. - The zero-count check happens before the division, so empty lists and lists containing only invalid values return
0.0without a division by zero.
Complexity
- Time: O(n), one pass with constant work per element.
- Space: O(1) extra, as only two accumulators are kept.
Reference solution
import math
from typing import List
def mean_earnings(earnings: List[float]) -> float:
total = 0.0
count = 0
for value in earnings:
if value is None or (isinstance(value, float) and math.isnan(value)):
continue
total += value
count += 1
if count == 0:
return 0.0
return float(round(total / count, 2))