Lesson 5.5 · Write it
Is it an index?
A functionPython or Java10 tests, 6 of them hidden
On a phone? Put the lines in order instead
Write a function that returns whether a whole number is an index of a list (an array in Java) of whole numbers.
- The indexes of a list start at 0 and stop one short of the number of values. A list of 3 values has the indexes 0, 1 and 2.
- Return
Truewhenindexis one of them andFalsewhen it is not (trueandfalsein Java). indexcan be any whole number. A negative number is never an index here.- The list can be empty. An empty list has no indexes.
Only the value your function returns is checked.
def valid_index(values: list[int], index: int) -> bool
Examples
Your function is tested on 10 cases: the 4 examples below, and 6 hidden ones that check the rules above.
- valid_index([3, 8, 5], 0) should return True: index 0, the first one (rule 1)
- valid_index([3, 8, 5], 2) should return True: the last index of three values (rule 1)
- valid_index([3, 8, 5], 3) should return False: the number of values is one past the last index (rule 1)
- valid_index([3, 8, 5], -1) should return False: a negative number (rule 3)
public static boolean validIndex(int[] values, int index)
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 10 cases: the 4 examples below, and 6 hidden ones that check the rules above.
- validIndex(new int[]{3, 8, 5}, 0) should return true: index 0, the first one (rule 1)
- validIndex(new int[]{3, 8, 5}, 2) should return true: the last index of three values (rule 1)
- validIndex(new int[]{3, 8, 5}, 3) should return false: the number of values is one past the last index (rule 1)
- validIndex(new int[]{3, 8, 5}, -1) should return false: a negative number (rule 3)