Lesson 26: Search the shelf
Look one by one
- A warehouse robot must find one box on a long shelf. It does not know where the box is.
- So it looks at the slots one by one, in order, from the first to the last. This is a linear search.
- The box is in a different slot on every map, and on one map it is not there at all.
Words for this lesson
| Word | Meaning |
|---|---|
| search | look for something |
| slot | one place on the shelf |
| flag | a variable that is True or False |
| found | seen; the search has worked |
Two ways to search
| Search | Stops |
|---|---|
for loop |
after the last slot, every time |
while loop with a flag |
at the box, or after the last slot |
- The
whilesearch is faster when the box is near the start.
A search in a list
from vexcode_vr import *
def main():
boxes = ["red", "red", "blue", "red"]
position = 0
for i in range(len(boxes)):
if boxes[i] == "blue":
position = i + 1
brain.print(position)
vr_thread(main)
- The brain prints 3: the blue box is the third one. (The list counts from 0, so slot =
i + 1.)
In the exam
- 0478/22/F/M/24 Q3(a): 50 numbers are in the array
Values[1:50]. Input a number and use a linear search to find it; output its position, or "Not found". - The mark scheme's answer has the same plan as your first task: set the location to 0 before the loop, compare each item with the number inside the loop and keep its index, then after the loop output the location, or "Not found" if it is still 0.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
A shelf has 6 slots, 200 mm apart, and each slot has a box. Most boxes are red. Find the blue one: drive to each slot with a for loop and look with the down eye. Remember the slot number of the blue box, and at the end print Found at and the number, for example Found at 4. On one map there is no blue box: then print Not found.
Clique em Executar para ver a saída aqui.
Dificuldade 4/5 · Moedas 280 + pequeno bônus na primeira conclusão hoje
Checking every slot wastes time when the box is near the start. Use a while loop with a flag: keep going while not found e slot < 6. When the down eye sees blue, set found = True. The robot must stop on the blue box, then print Found at and the slot, or Not found.
Clique em Executar para ver a saída aqui.