Programming
IB Computer Science HL Topic 6 10:09 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.
星期一,一位顾客输入了表示二的英文单词,而不是数字 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 Python input returns a string, we cast it with int for whole numbers or float for decimal numbers before doing arithmetic.
由于 Python 的 input 返回字符串,我们在进行算术运算前将整数输入用 int 转换,将小数输入用 float 转换。
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 为止,但不包含索引 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.
异常是程序运行时引发的错误,例如将表示二的英文单词传给 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 为偶数时,就将它加到总和中。
So 2 makes the total 2, and 4 makes it 6.
所以加上 2 后总和为 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 have quadratic worst-case time, but this bubble sort has a linear best case because it stops early.
两者的最坏情况时间复杂度都是平方级,但这种冒泡排序能够提前停止,因此最佳情况时间复杂度是线性级。
Compare their swaps and their best and worst cases.
比较它们的交换次数以及最佳和最坏情况。
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.
比较之前将分数转换为整数,并保存目前为止见到的最高分及对应姓名。
For Higher Level, a recursive function calls itself on a smaller version of the same problem.
对于 Higher Level,递归函数会针对同一问题规模更小的形式调用自身。
Total of a list is its first item plus the total of the rest.
列表的总和等于第一项加上其余部分的总和。
The base case, an empty list, returns 0 directly.
基本情况是空列表,直接返回 0。
Each call waits on the call stack with its own variables, until the base case returns.
每次调用都带着自己的变量在调用栈中等待,直到基本情况返回。
Then the values come back up, 2, then 9, then 13.
然后各个值逐层返回,先是 2,然后是 9,最后是 13。
Power of 3 and 3 calls itself with exponents 2, 1 and 0, four calls in all, and returns 27.
以 3 为底、3 为指数的幂函数会以指数 2、1 和 0 调用自身,总共调用四次,并返回 27。
Recursion is often shorter and matches the problem's definition, but each call uses a stack frame, so a very deep recursion, or one with no base case, overflows the stack.
递归通常更简短,也符合问题的定义,但每次调用都会使用一个栈帧,所以递归层数很深,或者没有基本情况时,会导致栈溢出。
It is natural for trees, nested folders and quicksort, which averages n log n.
递归很适合处理树、嵌套文件夹和快速排序;快速排序的平均复杂度为 n log n。
Try these.
试试这些题。
The string Programming has length 11, its slice from 3 to 7 is gram, and the first g is at index 3.
由字母 P、r、o、g、r、a、m、m、i、n、g 组成的字符串长度为 11,从 3 到 7 的切片是 g、r、a、m,第一个 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。
Explain a stack or queue by its order, its operations and a real use.
解释栈或队列时,要说明其顺序、操作和一个实际用途。
And for recursion, name the base case, the recursive case, and how each call moves towards the base case.
对于递归,要指出基本情况、递归情况,以及每次调用如何向基本情况靠近。
Comments
No comments yet. Be the first to ask or share something.