Skip to content
ExamSpine

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.

  1. 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.
  2. Return True when index is one of them and False when it is not (true and false in Java).
  3. index can be any whole number. A negative number is never an index here.
  4. 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)

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)
solution.pySolution.java