Searching, max and min
Python for IGCSE CS Lesson 10 2:07 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A linear search looks at each item in turn until it finds what it wants, and stops as soon as it finds it.
线性查找逐个检查每一个元素,直到找到想要的那个, 一找到就立刻停下。
The syllabus names it, so expect the phrase on the paper.
考纲给它起了名字,所以考卷上会出现这个说法。
Its strength is that it asks nothing of the data — any order, any values, any length.
它的长处是对数据毫无要求——任何顺序、任何值、任何长度。
Its cost is the other side of that: if the thing is not there, it will have looked at every single item.
而它的代价正是这一点的另一面: 如果那个东西不在里面,它会把每一个元素都看一遍。
Finding the largest value has exactly one hard decision, and it is the first line.
求最大值只有一个真正需要决定的地方,而它就在第一行。
It is tempting to start it at nought and then keep anything bigger.
人很容易把它初始化为 0,然后保留任何更大的数。
Look at what that does to a list where every number is negative: the answer comes out as nought, a value that is not even in the list.
看看在一个全是负数的列表上会发生什么: 答案变成了 0,而这个值根本不在列表里。
Start from the first item instead — that is guaranteed to be a real member.
应该从第一个元素开始——它一定是列表里真实存在的成员。
From there it is a competition.
从那里开始,这就是一场比赛。
Walk the list, and whenever an item beats the one you are holding, remember it instead.
遍历列表,每当有一个元素胜过你手里拿着的那个, 就改记住新的那个。
Watch the box: it starts at four, changes to nine, and then nothing else beats it.
看那个盒子:它从 4 开始,变成 9,之后再没有谁能胜过它。
And here is the neat part — change one symbol, greater-than to less-than, and the same four lines find the minimum instead.
而漂亮的地方在这里—— 把一个符号从大于改成小于, 同样这四行代码就变成了求最小值。
The tasks tell you not to use Python's own max and min, and that is not arbitrary.
题目要求你不要用 Python 自带的 max 和 min,这不是刁难。
The exam asks for the method, not the answer.
考试要的是方法,不是答案。
Pseudocode has no max function, so writing the loop IS the question — and a student who only knows the shortcut has nothing to write on the paper.
伪代码里没有 max 函数, 所以"写出这个循环"本身就是那道题—— 而一个只会用捷径的学生,在考卷上没有东西可写。
Read the two side by side; they are the same four steps.
把两边并排读一读;它们是同样的四个步骤。
Four things to take with you.
带走四点。
One: a linear search checks each item in turn.
第一:线性查找逐个检查每一个元素。
Two: for a maximum, start from the first item, never from nought.
第二:求最大值时,从第一个元素开始,绝不要从 0 开始。
Three: the same loop with the test flipped finds the minimum.
第三:同一个循环,把判断反过来,就得到最小值。
Four: starting at nought breaks on negative numbers.
第四:从 0 开始,在负数上就会出错。
Now write all three.
现在把三个都写出来。