This warm-up comes from a timed online assessment for a data science role. Write a function average(table) that returns the arithmetic mean of the numbers in the list table. If the list is empty, return 0.
Function Signature
def average(table: list[int]) -> float:
Rules
-
For a non-empty list, return the sum of the elements divided by the number of elements, as a floating-point number (IEEE 754 double precision).
-
For an empty list, return
0.0
.
-
Do not round the result.
Constraints
-
0 <= len(table) <= 10^5
-
-10^6 <= table[i] <= 10^6
-
The sum of the elements is at most
10^11
in absolute value, so it is exact in both 64-bit integers and double precision; the expected result is that exact sum divided by the length, correctly rounded to a double.
Examples
Example 1
-
Input:
table = [3, 4, 8]
-
Output:
5.0
Example 2
-
Input:
table = []
-
Output:
0.0
-
Explanation: An empty list has no mean; the specification asks for 0 instead of an error.
Example 3
-
Input:
table = [-2, 2, 1]
-
Output:
0.3333333333333333