Lesson 5.8 · Write it
The average
A functionPython or Java9 tests, 6 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the average (the mean) of a list (an array in Java) of whole numbers.
- The list always has at least one value.
- The values are whole numbers from -1000000 to 1000000, and can be negative. The list has at most 1000 values.
- Return the average as a decimal number, and do not round it: the average of 2 and 3 is 2.5, not 2.
Only the number your function returns is checked.
def average(values: list[int]) -> float
Examples
Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.
- average([2, 3]) should return 2.5: an average that is not a whole number (rule 3)
- average([4]) should return 4.0: one value is its own average
- average([-1, -2]) should return -1.5: negative values (rule 2)
public static double average(int[] values)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 9 cases: the 3 examples below, and 6 hidden ones that check the rules above.
- average(new int[]{2, 3}) should return 2.5: an average that is not a whole number (rule 3)
- average(new int[]{4}) should return 4.0: one value is its own average
- average(new int[]{-1, -2}) should return -1.5: negative values (rule 2)