KatInterview

Mean of a Numeric List with Empty-Input Fallback

Math & Bit ManipulationAuto-graded · 24 test cases
EasyAuto-gradedMath & Bit Manipulationarraysmathedge-cases

Last updated

Compute the arithmetic mean of a list of numbers, returning 0 for an empty list, testing basic edge-case handling and complexity reasoning.

Mean with a Safe Default

You are building a small utility for a data-processing step. Given a list of numbers, it must report the arithmetic mean of the values.

Implement mean_or_zero(values), which takes a list of numbers (integers and/or floats) and returns:

  • The arithmetic mean, meaning the sum of all elements divided by the number of elements, when the list has at least one element.
  • Exactly 0 when the list is empty, so that callers never hit a division-by-zero error.

Notes

  • Use ordinary Python arithmetic. The result for a non-empty list is the true division of the sum by the count, so it may be a float even when the inputs are all integers. For example, a result of 3.0 is considered equal to 3.
  • Negative numbers and zeros are valid inputs and are treated like any other value.
  • Every element of the input is guaranteed to be a real number. You do not need to handle None, NaN, strings, or other non-numeric items.

Constraints

  • 0 <= len(values) <= 10^6
  • Each element is a finite integer or float.
  • The input is a Python list.
  • Aim for a single pass over the data and constant extra memory.

Examples

Example 1

Input: mean_or_zero([1, 2, 3, 4, 5])

Output: 3

Example 2

Input: mean_or_zero([])

Output: 0

Example 3

Input: mean_or_zero([1.5, 2.5, 3.5])

Output: 2.5

Example 4

Input: mean_or_zero([-2, 0, 2])

Output: 0

Hints

Hint 1

Handle the empty list first, before any division takes place.

Hint 2

For a non-empty list, the mean is the sum of the elements divided by the length. Python's built-in sum and len do this for you.

Hint 3

One pass over the data is enough, so the work is linear in the list length and the extra memory is constant.