Lesson 5.7 · Write it
Where it appears
A functionPython or Java8 tests, 5 of them hidden
On a phone? Put the lines in order instead
Write a function that returns the indexes at which a target value appears in a list (an array in Java) of whole numbers.
- Return a list of indexes, in rising order.
- When the target does not appear, return an empty list.
- The list of values can be empty, and has at most 20 values. Every value, and the target, is between -1000 and 1000.
- In Java, return an
ArrayList<Integer>.
Only the list your function returns is checked.
def positions_of(values: list[int], target: int) -> list[int]
Examples
Your function is tested on 8 cases: the 3 examples below, and 5 hidden ones that check the rules above.
- positions_of([5, 3, 5, 8], 5) should return [0, 2]: the target appears twice, at indexes 0 and 2 (rule 1)
- positions_of([5, 3, 5, 8], 4) should return []: the target does not appear (rule 2)
- positions_of([7, 7, 7], 7) should return [0, 1, 2]: every value is the target, so every index is returned (rule 1)
public static ArrayList<Integer> positionsOf(int[] values, int target)
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.
- positionsOf(new int[]{5, 3, 5, 8}, 5) should return [0, 2]: the target appears twice, at indexes 0 and 2 (rule 1)
- positionsOf(new int[]{5, 3, 5, 8}, 4) should return []: the target does not appear (rule 2)
- positionsOf(new int[]{7, 7, 7}, 7) should return [0, 1, 2]: every value is the target, so every index is returned (rule 1)