Searching & max / min · 查找与最大 / 最小值
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Linear search
- A linear search looks at each item in turn until it finds the target.
- It is a named standard method in the syllabus.
- Use a loop and remember when you find a match.
中文
线性查找
- 线性查找(linear search)依次查看每个元素,直到找到目标。
- 它是考纲里有名字的标准方法。
- 用一个循环,找到匹配时记下来。
nums = [4, 9, 2, 7]
target = 9
found = False
for n in nums:
if n == target:
found = True
print(found) # True
Explore · 探索
Linear search, step by step · 线性查找,一步一步
A linear search checks each item in turn until it finds the target. · 线性查找逐个检查,直到找到目标。
English
Finding the maximum
- Start by assuming the first item is the biggest.
- Then check the rest; if one is bigger, remember it instead.
中文
找最大值
- 先假设第一个元素最大。
- 再检查其余的;如果有更大的,就改记它。
nums = [4, 9, 2, 7]
biggest = nums[0]
for n in nums:
if n > biggest:
biggest = n
print(biggest) # 9
English
Finding the minimum
- The same idea, but keep the smallest value seen so far.
中文
找最小值
- 同样的想法,但保留到目前为止见过的最小值。
nums = [4, 9, 2, 7]
smallest = nums[0]
for n in nums:
if n < smallest:
smallest = n
print(smallest) # 2
English
In the exam: standard methods
- Linear search and finding maximum / minimum / average are named in section 7.
中文
在考试里:标准方法
- 线性查找、找最大 / 最小 / 平均值,都在第 7 章里有名字。
Found ← FALSE
FOR I ← 1 TO 4
IF Number[I] = Target
THEN
Found ← TRUE
ENDIF
NEXT I
English
Common mistakes
- Linear search checks each item in turn until it finds the target.
- For max or min, start from the first item, then compare the rest against it.
中文
常见错误
- 线性查找逐个检查,直到找到目标。
- 求最大或最小,从第一个元素开始,再用其余的和它比较。
English
Now you try
- Loop through the list to search or compare.
- Press Check answer to test your code.
中文
现在轮到你
- 遍历列表来查找或比较。
- 按检查答案来测试你的代码。
Write contains(nums, target) that returns True if target is in the list, using a linear search · 线性搜索 loop (do not use the in keyword). · 写一个 contains(nums, target),用线性查找循环判断 target 是否在列表中,在则返回 True(不要用 in 关键字)。
Click Run to see the output here. · 点击“运行”查看此处输出。
The list nums is set. Find the largest value with a loop and store it in biggest (do not use max()). · 列表 nums 已设好。用循环找出最大的值,存进 biggest(不要用 max())。
Click Run to see the output here. · 点击“运行”查看此处输出。
Find the smallest value in nums with a loop and store it in smallest (do not use min()). · 用循环找出 nums 中最小的值,存进 smallest(不要用 min())。
Click Run to see the output here. · 点击“运行”查看此处输出。