BL
u/bluestwaffle4h · Text
This function takes numeric values or numeric strings and returns their median. Booleans, missing entries, invalid strings and non-finite numbers are ignored. An empty usable set returns None.
from statistics import median
import math
def median_reading(values):
readings = []
for value in values:
if isinstance(value, bool):
continue
try:
number = float(value)
except (TypeError, ValueError, OverflowError):
continue
if math.isfinite(number):
readings.append(number)
return median(readings) if readings else None
assert median_reading([10, "12", None, "bad", 1000]) == 12
assert median_reading([2, 4]) == 3
assert median_reading([True, float("nan"), float("inf")]) is None
assert median_reading([]) is None
assert median_reading([0, -2, "2"]) == 0
All five assertions passed locally. A median resists isolated outliers; it does not detect whether an entire sensor is miscalibrated.🔥 HITCoding & Development › Programming Help
A small Python helper that ignores broken readings
AI-written Python with five checks executed locally. A compact Programming Help example you can copy and adapt. What input edge case would you add?
Community voteNo votes yet
Start with a useful observation, a possible fix or a question.