Programming
IB Computer Science SL Topic 6 9:08 English narration · English and 中文 subtitles you can switch
Chapters
Transcript
A shop's checkout program has run for a month.
一家商店的收银程序已经运行了一个月。
On Monday a customer types the word two instead of the digit 2, and the program crashes.
周一,一位顾客输入了由字母 t、w、o 组成的英文单词,而不是数字 2,程序便崩溃了。
Nothing in the code changed; the input did.
代码没有任何变化;变化的是输入。
This topic builds the programming toolkit, from data types and data structures to searching, sorting and files, so that programs work for every input they meet.
本主题将介绍从数据类型和数据结构到搜索、排序和文件的编程工具,让程序面对各种输入都能正常运行。
A variable is a named store whose value can change; a constant, written in capitals, should not.
变量是有名称的存储单元,其值可以改变;用大写字母表示的常量则不应改变。
Every value has a data type.
每个值都有数据类型。
Integers count, reals measure, Booleans hold true or false, and strings hold text.
整数用于计数,实数用于度量,布尔值为真或假,字符串用于存放文本。
Because input always returns a string, we cast it with int before doing arithmetic.
由于 input 返回的总是字符串,因此做算术运算前要用 int 进行类型转换。
Seven divided by two is 3.5, integer division gives 3, and modulo gives the remainder, 1.
7 除以 2 等于 3.5,整数除法得到 3,取模得到余数 1。
A string is a sequence of characters indexed from zero.
字符串是由字符组成的序列,索引从零开始。
The code ib-2027 has length 7, and index 0 is the letter i.
字符串 ib-2027 的长度为 7,索引 0 对应字母 i。
The slice from 3 to 7 runs up to, but not including, index 7, giving 2027.
从 3 到 7 的切片包含起始位置,但不包含索引 7,得到 2027。
Strings are immutable, so upper returns a new string and leaves the original unchanged.
字符串是不可变的,所以 upper 返回一个新字符串,原字符串保持不变。
Find returns minus one when the text is not there.
找不到文本时,find 返回负一。
An exception is an error raised while a program runs, such as a ValueError when int is given the word two.
异常是程序运行时产生的错误,例如把由字母 t、w、o 组成的英文单词传给 int 时出现的 ValueError。
Unhandled, it stops the program.
如果不处理,异常会使程序停止。
Here the cast sits inside try.
这里,类型转换放在 try 中。
If it fails, except prints a message and the loop asks again; if it succeeds, break leaves the loop.
如果转换失败,except 就输出一条消息,循环再次询问;如果成功,break 就退出循环。
A finally block, if present, runs either way, and is used to close files.
如果有 finally 代码块,无论哪种情况它都会运行,可用于关闭文件。
A syntax error, such as a missing colon, is reported before the program runs.
语法错误,比如缺少冒号,会在程序运行前被报告。
A runtime error appears while it runs, as an exception, such as an index past the end of a list.
运行时错误在程序运行过程中以异常的形式出现,例如列表索引超出范围。
A logic error is never reported at all.
逻辑错误则完全不会被报告。
The program runs, but the output is wrong, perhaps because less-than was written where less-than-or-equal was meant.
程序能够运行,但输出有误,可能是因为本该写小于或等于,却写成了小于。
A trace table records each variable after each step.
跟踪表记录每一步之后各变量的值。
Total starts at 0.
total 初始为 0。
The loop runs k from 1 to 4, because range stops before 5.
循环让 k 从 1 取到 4,因为 range 在 5 之前停止。
When k is even, it is added to the total.
当 k 为偶数时,就把它加到 total 中。
So 2 makes the total 2, and 4 makes it 6.
所以加上 2 后 total 为 2,再加上 4 后变为 6。
The output is 6.
输出是 6。
Print statements, breakpoints in a debugger, and stepping one line at a time are the other ways to find a logic error.
使用打印语句、在调试器中设置断点,以及逐行单步执行,也是查找逻辑错误的方法。
Each value has a data type: integer, like 7; real, like 3.5; character, like A; string, like hello; and Boolean, true or false.
每个值都有数据类型:整数,例如 7;实数,例如 3.5;字符,例如 A;字符串,例如由字母 h、e、l、l、o 组成的字符串;以及布尔值,真或假。
The type decides how the value is stored and which operations make sense.
类型决定了值如何存储,以及可以对它进行哪些有意义的操作。
A trace table has a column for each variable, here count and total, and one for the output.
跟踪表中每个变量都有一列,这里是 count 和 total,输出也有一列。
Each time a value changes, write a new row.
每当一个值发生变化,就写一新行。
Tracing by hand shows exactly what the algorithm does, and where it goes wrong.
手动跟踪可以准确显示算法做了什么,以及哪里出了错。
A static data structure, like an array in Java or C, has a size fixed when it is created.
静态数据结构,例如 Java 或 C 中的数组,大小在创建时就固定了。
Its memory is reserved in advance, so some may be wasted, and adding to a full one overflows.
它的内存是预先分配的,因此可能会有浪费,而且向已满的结构添加数据会导致上溢。
A dynamic structure, like a Python list, grows and shrinks as the program runs, using memory as needed, though growing can take extra work.
动态数据结构,例如 Python 列表,会随着程序运行而增长或缩小,按需使用内存,不过扩容可能需要额外操作。
A two-dimensional array is a table stored as a list of rows.
二维数组是以行列表形式存储的表格。
The first index picks the row and the second the column, so grid one two is row 1, column 2, which holds 5.
第一个索引选择行,第二个选择列,所以 grid[1][2] 位于第 1 行、第 2 列,存放的值是 5。
To add up row 1, loop over its columns, 2 plus 8 plus 5 plus 3, which is 18.
要计算第 1 行的总和,就遍历该行的各列,2 加 8 加 5 加 3,等于 18。
To visit every cell, nest two loops, rows outside and columns inside.
要访问每个单元格,就嵌套两个循环,外层遍历行,内层遍历列。
Stacks and queues are abstract data types, defined by their operations.
栈和队列是由其操作定义的抽象数据类型。
A stack is last in, first out.
栈遵循后进先出原则。
Push and pop both act at the top, as in undo or a browser's back button.
压栈和弹栈都在栈顶操作,例如撤销功能或浏览器的后退按钮。
A queue is first in, first out.
队列遵循先进先出原则。
Enqueue adds at the rear and dequeue removes from the front, as with print jobs.
入队在队尾添加元素,出队从队首移除元素,例如打印任务队列。
Removing from an empty structure is an underflow, and pushing onto a full fixed-size stack is an overflow.
从空结构中移除元素会发生下溢,向已满的固定大小的栈中压入元素会发生上溢。
Every algorithm is built from sequence, selection and iteration.
每个算法都由顺序、选择和迭代构成。
Use a for loop with range when you know how many repeats are needed, a while loop to repeat until something happens, and a for loop over a collection to visit each item once.
知道需要重复多少次时,使用带 range 的 for 循环;要重复执行直到某件事发生时,使用 while 循环;要依次访问集合中的每一项,使用遍历集合的 for 循环。
A while loop whose condition never becomes false runs for ever.
如果 while 循环的条件永远不会变为假,循环就会一直运行。
A function is a named block that takes parameters and may return a value.
函数是一个有名称的代码块,接收参数并且可以返回一个值。
Splitting a program into functions is modularity.
把程序拆分成函数就是模块化。
Total is a local variable, existing only while the function runs.
total 是局部变量,只在函数运行期间存在。
The docstring states the contract, a non-empty list in, its mean out.
文档字符串说明了约定:输入一个非空列表,输出其平均值。
Test against the contract with normal values, a boundary case such as a one-item list, and invalid input such as an empty list, which raises ZeroDivisionError.
根据这个约定进行测试,使用正常值、单元素列表这样的边界情况,以及空列表这样的无效输入;空列表会引发 ZeroDivisionError。
Big O notation describes how a cost grows with the input size n, dropping constants and smaller terms.
大 O 记号描述成本如何随输入规模 n 增长,忽略常数和低阶项。
Reading one array item is constant.
读取一个数组元素的成本是常数级。
Binary search is logarithmic, about ten steps for a thousand items.
二分搜索是对数级,对于一千个元素约需十步。
Linear search is linear, a thousand steps.
线性搜索是线性级,需要一千步。
Bubble and selection sort are quadratic, about a million.
冒泡排序和选择排序是平方级,约需一百万步。
Say whether you mean the worst, average or best case.
要说明你指的是最坏、平均还是最好情况。
Linear search checks each item in turn and works on any list.
线性搜索依次检查每个元素,适用于任何列表。
Binary search needs a sorted list.
二分搜索需要一个已排序的列表。
To find 23, low is 0 and high is 8, so mid is 4, holding 16.
要查找 23,low 为 0,high 为 8,所以 mid 为 4,该位置的值是 16。
That is too small, so low becomes 5.
这个值太小,因此 low 变为 5。
Mid is now 6, holding 38, too big, so high becomes 5.
现在 mid 为 6,该位置的值是 38,太大,因此 high 变为 5。
Mid is 5, and 23 is found.
mid 为 5,找到了 23。
Each probe discards half of what remains, which is why binary search is logarithmic.
每次查探都会排除剩余范围的一半,这就是二分搜索为对数级的原因。
Bubble sort compares neighbours and swaps them if they are out of order, so the largest item bubbles to the end each pass.
冒泡排序比较相邻元素,如果顺序不对就交换它们,因此每一趟最大的元素都会冒到末尾。
A swapped flag lets it stop early when a pass makes no swaps.
交换标志使它能在某一趟没有发生交换时提前停止。
Selection sort finds the smallest unsorted item and swaps it into the next place, making at most n minus one swaps.
选择排序找出未排序部分中最小的元素,将它交换到下一个位置,最多进行 n 减 1 次交换。
Both are quadratic, so compare them by swaps and early stopping, not by Big O.
两者都是平方级,因此应比较交换次数和能否提前停止,而不是比较大 O 记号。
Bubble sort compares each adjacent pair in the list.
冒泡排序比较列表中每一对相邻元素。
If a pair is out of order, like 5 then 2, it swaps them.
如果一对元素顺序不对,比如 5 在 2 前面,就交换它们。
After each pass the largest remaining value has bubbled to the end.
每一趟结束后,剩余元素中的最大值都会冒到末尾。
Repeat until a pass makes no swaps.
重复这一过程,直到某一趟没有发生交换。
Variables are lost when a program ends; a file keeps data between runs.
程序结束时变量会消失;文件则能在多次运行之间保存数据。
Opening with r reads from the start.
用 r 打开文件时从头开始读取。
Opening with w empties the file first, so the earlier contents are gone.
用 w 打开时会先清空文件,因此之前的内容会消失。
Opening with a appends to the end.
用 a 打开时会在末尾追加内容。
Use with so the file closes automatically, even if an exception occurs, and catch FileNotFoundError when reading a file that may be missing.
使用 with 可以让文件自动关闭,即使发生异常也是如此;读取可能不存在的文件时,要捕获 FileNotFoundError。
To find the best score, open the file for reading and loop over its lines.
要找出最高分,先打开文件进行读取,再遍历文件的各行。
Each line ends in a newline, so strip removes it, and split on the comma breaks it into a name and a score.
每行都以换行符结尾,所以用 strip 移除它,再按逗号用 split 将其拆分成姓名和分数。
Cast the score to an integer before comparing, and keep the best name and score seen so far.
比较前把分数转换为整数,并记录目前为止最高的分数及对应的姓名。
Try these.
试试看。
The string Programming has length 11, its slice from 3 to 7 is gram, and the first g is at index 3.
字符串 Programming 的长度是 11,从 3 到 7 的切片是 gram,第一个 g 的索引是 3。
After pushing 10, 20 and 30, popping, and pushing 40, the top is 40.
依次压入 10、20 和 30,弹出一个元素,再压入 40 后,栈顶是 40。
A binary search for 31 compares with 19, then 31.
用二分搜索查找 31 时,先与 19 比较,再与 31 比较。
And the bubble sort passes give 3 6 2 8, then 3 2 6 8, then 2 3 6 8.
冒泡排序各趟的结果依次是 3 6 2 8、3 2 6 8、2 3 6 8。
Check yourself before you answer.
回答前先自查。
A trace table needs a new row each time a variable changes, with output shown separately.
跟踪表中,每次变量发生变化都需要新的一行,输出要单独列出。
State that Python indexes from zero.
说明 Python 的索引从零开始。
For binary search, say the list must be sorted and give low, high and mid at every probe.
对于二分搜索,要说明列表必须已排序,并给出每次查探时的 low、high 和 mid。
And explain a stack or queue by its order, its operations and a real use.
解释栈或队列时,要说明其顺序、操作和一个实际用途。
Comments
No comments yet. Be the first to ask or share something.