Lesson 5.6 · Write it
Swap the ends
A functionPython or Java7 tests, 4 of them hidden
On a phone? Put the lines in order instead
Write a function that swaps the first and last values of a list (an array in Java) of whole numbers, and returns the list.
- The list has between 1 and 20 values.
- After the swap, the value that was first is last, and the value that was last is first. Every other value stays at its index.
- A list of one value comes back unchanged.
Only the list your function returns is checked.
def swap_ends(values: list[int]) -> list[int]
Examples
Your function is tested on 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- swap_ends([3, 8, 5]) should return [5, 8, 3]: the ends change places and the middle value stays (rule 2)
- swap_ends([7]) should return [7]: one value (rule 3)
- swap_ends([1, 2, 6, 4]) should return [4, 2, 6, 1]: four values: the two in the middle stay where they are (rule 2)
public static int[] swapEnds(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 7 cases: the 3 examples below, and 4 hidden ones that check the rules above.
- swapEnds(new int[]{3, 8, 5}) should return [5, 8, 3]: the ends change places and the middle value stays (rule 2)
- swapEnds(new int[]{7}) should return [7]: one value (rule 3)
- swapEnds(new int[]{1, 2, 6, 4}) should return [4, 2, 6, 1]: four values: the two in the middle stay where they are (rule 2)