Implement a Safe Average Function in Python
WaymoData Scientist · Online AssessmentLast updated
Implement a Python average function that returns zero for an empty list and explain its time and space complexity. Clarify numeric types, missing values, NaN behavior, streaming alternatives, precision concerns, and the tests needed for a reliable data utility.
Write a Python function average(table) that returns the arithmetic mean of a list of numbers and returns 0 when the list is empty. Explain the function's behavior, complexity, and any input assumptions you would clarify before using it in a data pipeline.
Constraints & Assumptions
- The required empty-list result is exactly
0. - A direct implementation with Python's built-in numeric operations is sufficient.
- Do not silently invent missing-value semantics; explain how
NoneorNaNwould be handled if they can appear.
Clarifying Questions to Ask
- Are integers and floating-point values both valid?
- Can the input contain
None,NaN, nonnumeric values, or an iterator rather than a list? - Should the function return an integer or floating-point zero for an empty input?
- Is numerical overflow or precision important for the expected data size?
Follow-up questions
- How would you adapt the function to ignore `None` values?
- How would you compute the mean of a stream that cannot be stored in memory?
- What happens when the input contains `float('nan')`?
- How would you test this function?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.