Fix the sensor normalizer for missing readings
Your task
An AI wrote a cleaning step that replaces the sensor's missing readings, coded as -999, with NaN and then normalizes the column. Pandas skips NaN when it computes the mean and the standard deviation, but the arithmetic keeps NaN in every missing row, so NaN reached the model without an error. The fix normalizes the observed readings and handles the missing ones on purpose.
An assistant wrote normalize_sensor_readings(readings, sentinel, impute_missing). It is in the editor. It has a bug. Find it and fix it.
Input and output:
readings: the sensor values, in order.sentinel: the value that marks a missing reading. Different sensors use different sentinels.impute_missing: true to fill missing readings in, false to drop them.- Return the normalized values.
Rules the tests check:
- A reading is missing when it equals
sentinel. Every other reading is observed. - If no reading is observed, return an empty list.
- Compute the mean and the population standard deviation of the observed readings only: divide by their count, not the count minus 1. If the standard deviation is 0, use 1.
- Go through the readings in input order. An observed reading becomes the reading minus the mean, divided by the standard deviation. A missing reading becomes 0 when
impute_missingis true, which is the same as filling it with the mean, and is left out when it is false. - Answers within 0.000001 of the expected values pass.
Examples
normalize_sensor_readings(readings: list[float], sentinel: float, impute_missing: bool) -> list[float]Example 1
Input
normalize_sensor_readings([2, -999, 6], -999, True)Output
[-1, 0, 1]Example 2
Input
normalize_sensor_readings([2, -999, 6], -999, False)Output
[-1, 1]Example 3
Input
normalize_sensor_readings([0, 0, -999, 0, 0, 5], -999, True)Output
[-0.5, -0.5, 0, -0.5, -0.5, 2]