Lesson 21: Find the way home
Remember the way
- A robot that delivers a parcel must also find its way back.
- The robot can keep its moves in a list. On the way back it does the moves again, but last first.
- This is how the "back" button in a web browser works too: the last page you saw is the first one you go back to.
Words for this lesson
| Word | Meaning |
|---|---|
| list | many values in order: ["L", "F", "R"] |
| append | add a value to the end of a list |
| reverse | turn the order round: last becomes first |
| stack | a list where the last value in is the first value out |
Out and back
| Way out | Way back (list reversed) |
|---|---|
| L: turn left | F: drive 250 mm |
| F: drive 250 mm | R: turn left |
| R: turn right | F: drive 250 mm |
| F: drive 250 mm | L: turn right |
- Before the way back, the robot turns round 180°. It now faces the other way, so every left turn becomes a right turn, and every right turn becomes a left turn.
A list in Python
from vexcode_vr import *
def main():
moves = []
moves.append("L")
moves.append("F")
moves.append("R")
brain.print("".join(moves))
brain.new_line()
moves.reverse()
brain.print("".join(moves))
vr_thread(main)
- The brain prints
LFR, thenRFL.
In the exam
A-Level Computer Science (9618) asks about the stack, an abstract data type:
- A stack is LIFO: last in, first out.
- Push puts a value on the top (your
append); pop takes the top value off. - A top pointer shows where the top of the stack is.
- Uses: going back to earlier steps (the way home, the browser "back" button, "undo") and calling procedures.
Kesulitan 4/5 · 280 koin + bonus kecil pada penyelesaian pertama hari ini
The robot follows the road signs from lesson 13 (red: turn left, blue: turn right, green: stop). Now it should also remember the way. Make an empty list turns. Each time the robot turns, add "L" or "R" to the list with append. At the green tile, print Turns: and the letters, for example Turns: LLR.
Klik Jalankan untuk melihat output di sini.
Kesulitan 5/5 · 400 koin + bonus kecil pada penyelesaian pertama hari ini
Now the robot must also drive back to the black home tile. Keep every move in a list moves: "L", "R" and also "F" for each forward drive. At the green tile, turn round (180°), reverse the list with moves.reverse(), and do each move again: "F" drives forward 250 mm, but each turn is now the other way ("L" turns right, "R" turns left).
Klik Jalankan untuk melihat output di sini.