Lesson 5.5 · Write it
Middle value
A functionPython or Java8 tests, 5 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the middle value of a list (an array in Java) of whole numbers.
- The list has an odd number of values, and at least one.
- The middle value is the one with the same number of values before it as after it.
- The values are in no particular order. The middle value is about where a value sits in the list, not how big it is.
Only the value your function returns is checked.
def middle_value(values: list[int]) -> int
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- middle_value([4, 9, 2]) should return 9: one value each side; 9 is in the middle although it is the largest (rule 3)
- middle_value([6]) should return 6: one value: nothing before it and nothing after it (rule 2)
- middle_value([5, 1, 3, 8, 7]) should return 3: two values each side; 3 is neither the largest nor the middle-sized value (rule 3)
public static int middleValue(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 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- middleValue(new int[]{4, 9, 2}) should return 9: one value each side; 9 is in the middle although it is the largest (rule 3)
- middleValue(new int[]{6}) should return 6: one value: nothing before it and nothing after it (rule 2)
- middleValue(new int[]{5, 1, 3, 8, 7}) should return 3: two values each side; 3 is neither the largest nor the middle-sized value (rule 3)