Quick Overview

This question evaluates proficiency with basic programming fundamentals including numeric computation, handling edge cases such as empty inputs, input immutability, and data type consistency.

Implement Safe Average Function

Company: Waymo

Role: Data Scientist

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Online Assessment

Write a Python function `average(values)` that returns the arithmetic mean of a list of numbers. Requirements: - If `values` is empty, return `0`. - The input is a flat list of numeric values such as integers or floats. - Do not mutate the input list. Examples: - `average([1, 2, 3])` returns `2.0` - `average([-1, 1])` returns `0.0` - `average([])` returns `0`

Overview: This question evaluates proficiency with basic programming fundamentals including numeric computation, handling edge cases such as empty inputs, input immutability, and data type consistency.

Write a function `solution(values)` that returns the arithmetic mean of a flat list of numeric values. The arithmetic mean is the sum of all values divided by the number of values. If the list is empty, return `0`. The function must not mutate the input list.

Constraints

  • 0 <= len(values) <= 100000
  • Each element of values is an integer or float
  • Values are finite numeric values
  • The input list must not be mutated

Examples

Input: ([1, 2, 3],)

Expected Output: 2.0

Explanation: The sum is 6 and there are 3 values, so the average is 6 / 3 = 2.0.

Input: ([-1, 1],)

Expected Output: 0.0

Explanation: The sum is 0 and there are 2 values, so the average is 0 / 2 = 0.0.

Hints

  1. Handle the empty list case before dividing to avoid division by zero.
  2. You only need the total sum and the number of elements.

Loading coding console...