Lesson 26: Search the shelf
이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
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 |
English
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.
English
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.)
English
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.
난이도 3/5 · 200코인 + 오늘 첫 완료 시 작은 보너스 추가
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.
출력을 보려면 '실행'을 클릭하세요.
난이도 4/5 · 280코인 + 오늘 첫 완료 시 작은 보너스 추가
Checking every slot wastes time when the box is near the start. Use a while loop with a flag: keep going while not found 및 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.
출력을 보려면 '실행'을 클릭하세요.