Lesson 5.9 · Write it
Position of the largest
A functionPython or Java10 tests, 5 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the position (the index) of the largest value in a list (an array in Java) of whole numbers. Positions start at 0.
- If the largest value appears more than once, return the position of the first one.
- The list always has at least one value.
- The values can be negative.
- Write the search yourself. The shortcuts listed with this question are not allowed.
Only the number your function returns is checked.
def index_of_largest(values: list[int]) -> int
You cannot use these in this question:
- max()
- min()
- sorted()
- .index()
- .sort()
- import heapq
Some exam questions ask you to write the search yourself, so practise the loop. The shortcuts listed are not allowed.
Examples
Your function is tested on 10 cases: the 5 examples below, and 5 hidden ones that check the rules above.
- index_of_largest([4, 9, 2]) should return 1: 9 is the largest, at position 1
- index_of_largest([7]) should return 0: one value, so position 0
- index_of_largest([9, 1, 9]) should return 0: the first 9 wins (rule 1)
- index_of_largest([-5, -2, -9]) should return 1: all negative values (rule 3)
- index_of_largest([1, 5, 3]) should return 1: a later value smaller than the best so far
public static int indexOfLargest(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.
You cannot use these in this question:
- Math.max()
- Math.min()
- Arrays.sort()
- Arrays.parallelSort()
- Collections.max()
- Collections.min()
- .indexOf()
- .sort()
- .stream()
- .max()
- .min()
- import java.util.stream
Some exam questions ask you to write the search yourself, so practise the loop. The shortcuts listed are not allowed.
Examples
Your function is tested on 10 cases: the 5 examples below, and 5 hidden ones that check the rules above.
- indexOfLargest(new int[]{4, 9, 2}) should return 1: 9 is the largest, at position 1
- indexOfLargest(new int[]{7}) should return 0: one value, so position 0
- indexOfLargest(new int[]{9, 1, 9}) should return 0: the first 9 wins (rule 1)
- indexOfLargest(new int[]{-5, -2, -9}) should return 1: all negative values (rule 3)
- indexOfLargest(new int[]{1, 5, 3}) should return 1: a later value smaller than the best so far