Reverse a list end to end
A replay view shows the most recent reading first, so the buffer has to come back the other way round.
- The order reverses; the values themselves are untouched.
- An empty list and a single reading both come back as they went in.
reverse_readings(readings: list<int>) → list<int>
Where you start
def reverse_readings(readings: list[int]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
reverse_readings([1, 2, 3]) | [3, 2, 1] |
reverse_readings([1, 2, 3, 4]) | [4, 3, 2, 1] |
reverse_readings([7]) | [7] |
reverse_readings([]) | [] |
Hint
Put one index at each end. Swap what they point at, then step them towards each other until they meet.
Reference solution in Python
def reverse_readings(readings: list[int]) -> list[int]:
out = list(readings)
i, j = 0, len(out) - 1
while i < j:
out[i], out[j] = out[j], out[i]
i += 1
j -= 1
return out