Unit 3: Algorithms and Programming
单元 3:算法与编程
Trace code, build abstractions, and evaluate algorithms. This Big Idea accounts for 30–35% of the AP CSP multiple-choice exam.
追踪代码、构建抽象并评价算法。这个核心概念占 AP CSP 选择题考试的 30–35%。
Variables and Assignments
变量与赋值
- A variable is an abstraction that holds one value at a time. That value may be a list or another collection of values. (AAP-1.A.1)
- Meaningful variable names make code easier to read and help show what values represent. (AAP-1.A.2)
- Some languages use data types such as numbers, Booleans, lists, and strings. Choose a type suited to the value. (AAP-1.A.3, AAP-1.A.4)
- Assignment changes the value represented by a variable. In
a ← expression, evaluate the expression first, then assign a copy of the result toa. (AAP-1.B.1, AAP-1.B.2) - A variable holds its most recently assigned value. A later change to one variable does not change a value already copied to another. (AAP-1.B.3)
- 变量(variable)是一种抽象(abstraction),一次保存一个值。这个值可以是包含多个值的列表或其他集合。 (AAP-1.A.1)
- 有意义的变量名能提高代码的可读性,并帮助读者理解变量表示的值。 (AAP-1.A.2)
- 有些语言使用数据类型(data type),如数字、布尔值(Boolean)、列表(list)和字符串(string)。应选择适合该值的类型。 (AAP-1.A.3, AAP-1.A.4)
- 赋值(assignment)会改变变量表示的值。在
a ← expression中,先计算表达式(expression),再将结果的副本赋给a。 (AAP-1.B.1, AAP-1.B.2) - 变量保存最近一次赋给它的值。之后改变一个变量,不会改变已经复制到另一个变量中的值。 (AAP-1.B.3)
Representing values
表示值
A variable has associated storage for its value. A name such as score gives a reader more information than x when the value represents a score. A number can represent a count, while a Boolean can represent whether a condition is true or false. A list can hold several values as one variable's value.
变量有与之关联的数据存储空间。当值表示分数时,score 比 x 更能帮助读者理解其含义。数字可以表示数量,布尔值可以表示条件是真还是假。列表可以作为一个变量的值,容纳多个值。
Trace assignments in order
按顺序追踪赋值
On an exam, evaluate the right side using the current values, then update the variable on the left. Track each variable separately after every assignment. The arrow is an assignment operator, not a statement that the two sides must remain equal.
考试中,先用当前值计算箭头右侧,再更新左侧的变量。每次赋值后,分别记录各变量的值。箭头是赋值运算符(assignment operator),并不表示两侧必须一直相等。
What values does this code display?
这段代码显示哪些值?
score ← 1 savedScore ← score score ← 2 DISPLAY(savedScore) DISPLAY(score)
score ← 1assigns 1 toscore.savedScore ← scorecopies the current value, 1, intosavedScore.score ← 2changesscoreto 2. It does not changesavedScore.- The answer is 1 followed by 2. Each
DISPLAYalso adds a trailing space.
score ← 1将 1 赋给score。savedScore ← score将当前值 1 复制到savedScore。score ← 2将score改为 2,但不会改变savedScore。- 答案是先显示 1,再显示 2。每次
DISPLAY还会在值后添加一个空格。
A common wrong answer is that both displays show 2 because savedScore was assigned from score. Assignment copied the value at that moment; it did not create an ongoing link between the variables.
常见错误答案是两个显示值都是 2,理由是 savedScore 来自 score。赋值只复制当时的值,不会在两个变量之间建立持续关联。
An assignment can use the same variable on both sides. If score is 2, then score ← score + 1 first evaluates the right side to 3 and then stores 3. The old value is used to calculate the new value.
赋值语句的两侧可以使用同一个变量。如果 score 是 2,那么 score ← score + 1 会先将右侧计算为 3,再存入 3。旧值用于计算新值。
Data Abstraction
数据抽象
- A list is an ordered sequence of elements. Each element has a unique index. A string is an ordered sequence of characters. (AAP-1.C.1, AAP-1.C.2, AAP-1.C.4)
- Indices use natural numbers to reference positions in a list or string. On the exam, list indices run from 1 through the list’s length. (AAP-1.C.3, AAP-1.D.8)
- Data abstraction separates a data type’s abstract properties from its representation. Naming a collection lets code use it without referring to representation details. (AAP-1.D.1, AAP-1.D.2)
- A list can create a data abstraction that treats related items as one value. Data abstractions often contain different types of elements. Some languages call lists arrays. (AAP-1.D.3, AAP-1.D.5, AAP-1.D.6)
- Using a data abstraction can make a program easier to develop and maintain. (AAP-1.D.4)
[value1, value2]creates a list,[]creates an empty list, and list assignment copies the list. An invalid list index causes an error and terminates the program. (AAP-1.D.7, AAP-1.D.8)
- 列表(list)是元素(element)的有序序列,每个元素都有唯一的索引(index)。字符串(string)是字符的有序序列。(AAP-1.C.1, AAP-1.C.2, AAP-1.C.4)
- 索引用自然数表示列表或字符串中的位置。考试中,列表索引从 1 到列表长度。 (AAP-1.C.3, AAP-1.D.8)
- 数据抽象(data abstraction)将数据类型的抽象属性与其表示细节分开。给数据集合命名后,代码可以使用它,而不必涉及表示细节。 (AAP-1.D.1, AAP-1.D.2)
- 列表可以创建数据抽象,将相关项目作为一个值处理。数据抽象中常含有不同类型的元素。有些语言将列表称为数组(array)。 (AAP-1.D.3, AAP-1.D.5, AAP-1.D.6)
- 使用数据抽象可以使程序更容易开发和维护。 (AAP-1.D.4)
[value1, value2]创建列表,[]创建空列表,列表赋值会复制列表。无效的列表索引会导致错误并终止程序。 (AAP-1.D.7, AAP-1.D.8)
Sequences and indices
序列与索引
A variable can represent an entire list or string. In [20, 40, 60], the elements at indices 1, 2, and 3 are 20, 40, and 60. Order matters: the index identifies a position, not the value itself.
一个变量可以表示整个列表或字符串。在 [20, 40, 60] 中,索引 1、2、3 处的元素分别是 20、40、60。顺序很重要:索引标识的是位置,而不是值本身。
A string also has an order. For example, the characters in "CAT" are C, A, and T in that order.
字符串也有顺序。例如,"CAT" 中的字符依次是 C、A、T。
Lists as data abstractions
用列表实现数据抽象
A list gives a name to a collection of related values, so a program can work with the collection as one value. For example, a student profile list could contain a name, a number, and a color. The list’s meaning and ordered elements can be used without referring to the concrete details of how the data is represented.
列表为一组相关值提供一个名称,使程序可以将整个集合作为一个值处理。例如,学生资料列表可以包含姓名、数字和颜色。使用列表的含义和有序元素时,不必涉及数据如何表示的具体细节。
Grouping related data can make code easier to develop and maintain. On the exam, a list literal creates a new list, and assigning one list variable to another makes a copy.
将相关数据组织在一起,可以使代码更容易开发和维护。考试中,列表字面量(list literal)创建新列表,将一个列表变量赋值给另一个变量会创建副本。
The list stores a student’s name, a number, and a color. What does the program display?
这个列表存储学生的姓名、一个数字和一种颜色。程序会显示什么?
profile ← ["Mina", 3, "blue"] copy ← profile copy[2] ← 4 DISPLAY(profile[2]) DISPLAY(copy[2])
profilecontains three elements. Its second element is 3.copy ← profilecopies the list. Changingcopy[2]to 4 does not changeprofile[2].- The program displays 3, then 4. Each
DISPLAYadds a trailing space.
profile包含三个元素,第二个元素是 3。copy ← profile复制列表。将copy[2]改为 4 不会改变profile[2]。- 程序先显示 3,再显示 4。每个
DISPLAY都会在输出后添加一个空格。
copy does not change profile. Also, index 2 means the second element, not the third.
copy 的元素不会改变 profile。另外,索引 2 表示第二个元素,不是第三个。
profile[0] or profile[4] would cause an error and terminate the program. A list’s name hides representation details, but the programmer still needs to know what its positions mean.
profile[0] 或 profile[4] 会导致错误并终止程序。列表名称隐藏了表示细节,但程序员仍需知道各位置的含义。
Mathematical Expressions
数学表达式
- An algorithm is a finite set of instructions for a specific task. It can be expressed in natural language, diagrams, or pseudocode; programs implement algorithms using programming languages. (AAP-2.A.1, AAP-2.A.2, AAP-2.A.3)
- Every algorithm can be built from sequencing, selection, and iteration. (AAP-2.A.4)
- A code statement expresses an action. In a sequence, statements run in the order given. (AAP-2.B.1, AAP-2.B.2, AAP-2.B.6)
- An expression can contain values, variables, operators, or calls that return values. It evaluates to one value using the language's order of operations. (AAP-2.B.3, AAP-2.B.4, AAP-2.B.5)
- Write algorithms clearly and readably. The exam arithmetic operators are
+,-,*,/, andMOD;17 / 5is3.4. (AAP-2.B.7, AAP-2.C.1, AAP-2.C.3) a MOD bgives the remainder for integera ≥ 0and integerb > 0. Use mathematical order of operations:MODhas the same precedence as*and/. (AAP-2.C.2, AAP-2.C.4)
- 算法(algorithm)是完成特定任务的有限条指令。它可以用自然语言、图示或伪代码(pseudocode)表达;程序使用编程语言实现算法。(AAP-2.A.1、AAP-2.A.2、AAP-2.A.3)
- 任何算法都可以由顺序执行(sequencing)、选择(selection)和迭代(iteration)组合构建。(AAP-2.A.4)
- 代码语句(code statement)表达要执行的操作。在顺序执行中,语句按给出的顺序运行。(AAP-2.B.1、AAP-2.B.2、AAP-2.B.6)
- 表达式(expression)可以包含值、变量、运算符或有返回值的过程调用。它按照语言规定的运算顺序求出一个值。(AAP-2.B.3、AAP-2.B.4、AAP-2.B.5)
- 编写算法时要清晰、易读。考试的算术运算符(arithmetic operators)是
+、-、*、/和MOD;17 / 5等于3.4。(AAP-2.B.7、AAP-2.C.1、AAP-2.C.3) a MOD b求余数,其中a是大于等于 0 的整数,b是大于 0 的整数。使用数学中的运算顺序:MOD与*、/优先级相同。(AAP-2.C.2、AAP-2.C.4)
From instructions to code
从指令到代码
To describe a sequential algorithm without a programming language, list its steps in the order they should happen. For example: find the remainder when 17 is divided by 5, double that remainder, and add 3.4. Changing the order can change the result.
不用编程语言描述顺序算法时,按执行顺序列出步骤。例如:求 17 除以 5 的余数,将余数乘以 2,再加上 3.4。改变顺序可能改变结果。
In code, each statement carries out an action. An assignment evaluates its expression and stores the result. Clear names make the sequence easier to follow. Selection and iteration can also be combined with sequencing to construct algorithms.
在代码中,每条语句执行一个操作。赋值语句先求出表达式的值,再存储结果。清晰的名称使执行顺序更容易理解。选择和迭代也可以与顺序执行组合来构建算法。
Evaluate arithmetic expressions
求算术表达式的值
Evaluate parentheses first, then multiplication, division, and MOD, then addition and subtraction. Operators at the same precedence are evaluated left to right. For example, 17 MOD 5 is 2 because 17 divided by 5 leaves remainder 2.
先计算括号,再计算乘法、除法和 MOD,最后计算加法和减法。相同优先级的运算符从左到右计算。例如,17 MOD 5 等于 2,因为 17 除以 5 的余数是 2。
What value does this code display?
以下代码显示的值是多少?
number ← 17 remainder ← number MOD 5 number ← number / 5 result ← remainder * 2 + number DISPLAY(result)
numberstarts at 17. The next statement setsremainderto 2.number / 5is 3.4, so the third statement changesnumberto 3.4. The stored remainder stays 2.- Multiply before adding:
2 * 2 + 3.4is 7.4. The answer is7.4, displayed followed by a space.
number初始为 17。下一条语句将remainder设为 2。number / 5等于 3.4,因此第三条语句将number改为 3.4。已存储的余数仍是 2。- 先乘后加:
2 * 2 + 3.4等于 7.4。答案是7.4,显示时后面带一个空格。
Do not treat 17 / 5 as integer division and answer 3. On the exam reference sheet, division gives 3.4. Also, 17 MOD 5 gives the remainder 2, not the quotient.
不要把 17 / 5 当成整数除法而答 3。考试参考表中的除法结果是 3.4。另外,17 MOD 5 得到的是余数 2,而不是商。
Parentheses can change the remainder calculation. 17 MOD 5 * 2 evaluates left to right to 4, but 17 MOD (5 * 2) is 7. Trace each operation rather than assuming MOD always comes last.
括号可以改变求余的结果。17 MOD 5 * 2 从左到右计算,结果是 4;但 17 MOD (5 * 2) 的结果是 7。逐步追踪运算,不要以为 MOD 总是最后计算。
Strings
字符串
- String concatenation joins two or more strings end-to-end to make a new string. (AAP-2.D.1)
- Keep the characters and their order when finding the result. Spaces in the strings remain part of the result. (AAP-2.D.1)
- A substring is a contiguous part of an existing string. (AAP-2.D.2)
- On the exam, trace the exact result of joining strings or identify a substring. (AAP-2.D.1, AAP-2.D.2)
- 字符串拼接(string concatenation)将两个或更多字符串首尾相连,生成一个新字符串。(AAP-2.D.1)
- 求结果时要保留字符及其顺序。原字符串中的空格仍是结果的一部分。(AAP-2.D.1)
- 子串(substring)是已有字符串中连续的一部分。(AAP-2.D.2)
- 考试中要能追踪字符串拼接的准确结果,或识别子串。(AAP-2.D.1, AAP-2.D.2)
Joining and finding parts
拼接与查找部分
To evaluate a concatenation, place the strings in the given order. Joining "rain" and "bow" produces "rainbow". No space is added by the join itself.
计算拼接结果时,按给定顺序连接字符串。拼接 "rain" 和 "bow" 得到 "rainbow"。拼接本身不会添加空格。
A substring keeps consecutive characters from the original string in their original order. For example, "bow" is a substring of "rainbow", but "rnb" is not.
子串保留原字符串中连续的字符及其原有顺序。例如,"bow" 是 "rainbow" 的子串,但 "rnb" 不是。
After this code runs, what string results from joining first and second in that order? Is "bow" a substring of the result? What does the code display?
以下代码运行后,按顺序拼接 first 和 second 会得到什么字符串?"bow" 是结果的子串吗?代码会显示什么?
first ← "rain" second ← "bow" DISPLAY(first) DISPLAY(second)
firstis"rain"andsecondis"bow".- Joining them end-to-end gives
"rainbow". The consecutive characters at the end form"bow", so it is a substring. - Each
DISPLAYadds a trailing space. The displayed text israin bow, including a space afterbow. The code displays the two strings; it does not join them.
first是"rain",second是"bow"。- 首尾拼接得到
"rainbow"。末尾连续的字符构成"bow",因此它是一个子串。 - 每次
DISPLAY都会在末尾添加一个空格。显示的文本是rain bow,其中bow后也有一个空格。代码显示了两个字符串,并没有将它们拼接。
Do not answer "rain bow" for the concatenation of "rain" and "bow". Neither string contains a space. The space between separate displays comes from DISPLAY, not concatenation.
不要把 "rain" 和 "bow" 的拼接结果答成 "rain bow"。两个字符串都不含空格。分别显示时中间的空格来自 DISPLAY,不是拼接产生的。
Order and existing spaces both matter. Joining "bow" then "rain" gives "bowrain". Joining "rain " then "bow" gives "rain bow" because the first string already ends in a space.
顺序和已有的空格都很重要。先拼接 "bow" 再拼接 "rain",得到 "bowrain"。先拼接 "rain " 再拼接 "bow",得到 "rain bow",因为第一个字符串末尾已有空格。
Boolean Expressions
布尔表达式(Boolean expressions)
- A Boolean value is either true or false. (AAP-2.E.1)
- Relational operators compare values and produce a Boolean:
=,≠,>,<,≥, and≤. (AAP-2.E.2) - Logical operators produce a Boolean. Each operand is a Boolean value or expression. (AAP-2.F.1, AAP-2.F.5)
NOTreverses a Boolean value. (AAP-2.F.2)ANDis true only when both operands are true. (AAP-2.F.3)ORis true when at least one operand is true, including when both are true. (AAP-2.F.4)
- 布尔值(Boolean value)只有 true 或 false 两种。 (AAP-2.E.1)
- 关系运算符(relational operators)比较值并得到布尔值:
=、≠、>、<、≥和≤。 (AAP-2.E.2) - 逻辑运算符(logical operators)产生布尔值。每个操作数(operand)都是布尔值或布尔表达式。 (AAP-2.F.1, AAP-2.F.5)
NOT将布尔值取反。 (AAP-2.F.2)- 只有两个操作数都为 true 时,
AND才为 true。 (AAP-2.F.3) - 至少一个操作数为 true 时,
OR就为 true,包括两者都为 true 的情况。 (AAP-2.F.4)
Write and evaluate comparisons
编写和计算比较表达式
Use = for equal and ≠ for not equal. Use > and < for greater than and less than; ≥ and ≤ include equality. For example, if a and b are both 5, a = b and a ≥ b are true, but a > b is false.
用 = 表示相等,≠ 表示不相等。> 和 < 分别表示大于和小于;≥ 和 ≤ 包含相等。例如,如果 a 和 b 都是 5,a = b 和 a ≥ b 为 true,而 a > b 为 false。
Combine Boolean values
组合布尔值
To require both conditions, join them with AND. To require at least one, use OR. Use NOT to reverse a condition. Parentheses make the conditions being combined clear.
要求两个条件都成立时,用 AND 连接;要求至少一个成立时,用 OR。用 NOT 对条件取反。括号可以清楚地标明被组合的条件。
A value is inside the range from 3 through 8 if it meets both bounds. Trace the following code.
一个值同时满足两个边界条件,就在 3 到 8 的闭区间内。追踪以下代码。
x ← 3 y ← 9 inside ← (x ≥ 3) AND (x ≤ 8) outside ← (x < 3) OR (x > 8) either ← (x = 3) OR (y < 8) DISPLAY(inside) DISPLAY(outside) DISPLAY(either)
x ≥ 3andx ≤ 8are both true, soinsideis true.x < 3andx > 8are both false, sooutsideis false.x = 3is true andy < 8is false. One true operand makeseithertrue.- The displayed values are true, false, true, in that order. Each
DISPLAYadds a trailing space.
x ≥ 3和x ≤ 8都为 true,所以inside为 true。x < 3和x > 8都为 false,所以outside为 false。x = 3为 true,y < 8为 false。一个操作数为 true,就使either为 true。- 依次显示的值是 true、false、true。每次
DISPLAY都会在结果后加一个空格。
Do not say OR is false when both operands are true. It is inclusive: either one or both can be true. Also, = tests equality; ← assigns a value.
不要误认为两个操作数都为 true 时 OR 为 false。它是包含式的:一个或两个为 true 都可以。另外,= 用于判断相等;← 用于赋值。
For any value of x, NOT ((x ≥ 3) AND (x ≤ 8)) describes the same outside-range test as (x < 3) OR (x > 8). Check the endpoints: 3 and 8 are inside, not outside. Reversing the whole range condition changes both comparisons and changes AND to OR.
对任意 x,NOT ((x ≥ 3) AND (x ≤ 8)) 与 (x < 3) OR (x > 8) 表示相同的区间外判断。检查端点:3 和 8 在区间内,不在区间外。对整个范围条件取反时,两个比较都要反转,AND 也要变成 OR。
Conditionals
条件语句
- Selection chooses which parts of an algorithm run based on whether a condition is true or false. (AAP-2.G.1)
- A conditional changes the flow of control based on a Boolean expression. (AAP-2.H.1)
- In an
IFwithoutELSE, the block runs only when the condition is true. (AAP-2.H.2) - In an
IFwithELSE, the first block runs when the condition is true; otherwise, the second block runs. (AAP-2.H.3)
- 选择(selection)根据条件为真还是为假,决定执行算法的哪些部分。(AAP-2.G.1)
- 条件语句(conditional)根据布尔表达式(Boolean expression)改变控制流程(flow of control)。(AAP-2.H.1)
- 没有
ELSE的IF仅在条件为真时执行其代码块。(AAP-2.H.2) - 带
ELSE的IF在条件为真时执行第一个代码块,否则执行第二个代码块。(AAP-2.H.3)
Describe a decision
描述一个决策
You can express selection without code. For example: If the score is at least 70, display “Pass”; otherwise, display “Retry.” The condition determines which action is taken.
选择可以不用代码来表达。例如:如果分数至少为 70,显示“Pass”;否则显示“Retry”。条件决定采取哪个操作。
Trace the flow
追踪控制流程
Evaluate the condition first. Execute the chosen block, if there is one, then continue with the statements after the conditional. To determine the result, trace each conditional in order and check boundary values carefully.
先计算条件的值。如果有选中的代码块,就执行它,然后继续执行条件语句之后的语句。要确定结果,应按顺序追踪每个条件语句,并仔细检查边界值。
What does this code display?
这段代码显示什么?
score ← 70 IF(score ≥ 70) { DISPLAY("Pass") } ELSE { DISPLAY("Retry") } IF(score > 70) { DISPLAY("Bonus") } DISPLAY("Done")
score ≥ 70is true, so the first block displaysPass. TheELSEblock is skipped.score > 70is false. Its block is skipped because there is noELSE.- Execution continues and displays
Done. The answer isPass Done, with a space after each displayed value.
score ≥ 70为真,因此第一个代码块显示Pass,并跳过ELSE代码块。score > 70为假。由于没有ELSE,其代码块被跳过。- 程序继续执行并显示
Done。答案是Pass Done,每个显示的值后都有一个空格。
The wrong answer Pass Bonus Done treats 70 > 70 as true. A value is equal to itself, not greater than itself. Also, an ELSE runs only when its matching IF condition is false.
错误答案 Pass Bonus Done 把 70 > 70 当成了真。一个值等于自身,而不是大于自身。另外,ELSE 只在对应的 IF 条件为假时执行。
The two IF statements are separate decisions. With a score of 71, both conditions are true, so both Pass and Bonus are displayed. With a score of 69, the first condition is false and the ELSE displays Retry; the second condition is also false.
两个 IF 语句是独立的决策。分数为 71 时,两个条件都为真,因此 Pass 和 Bonus 都会显示。分数为 69 时,第一个条件为假,ELSE 显示 Retry;第二个条件也为假。
Nested Conditionals
嵌套条件语句(Nested Conditionals)
- A nested conditional is a conditional statement inside another conditional statement. (AAP-2.I.1)
- The outer branch determines whether the inner conditional is reached. (AAP-2.I.1)
- To find the result, trace the outer condition first, then trace any inner condition that is reached. (AAP-2.I.1)
- 嵌套条件语句是在一个条件语句(conditional statement)内部放置另一个条件语句。 (AAP-2.I.1)
- 外层分支(branch)决定程序是否会执行到内层条件语句。 (AAP-2.I.1)
- 求运行结果时,先追踪外层条件,再追踪实际执行到的内层条件。 (AAP-2.I.1)
Write and trace nested selection
编写并追踪嵌套选择
Place an IF statement inside the branch where its decision is needed. An ELSE belongs to the IF paired with it. Use the braces to see which statements are inside each branch.
把 IF 语句放在需要进行该判断的分支内。ELSE 属于与它配对的 IF。根据大括号判断哪些语句属于各个分支。
On an exam, follow only the branch selected at each level. If the outer branch containing the inner IF is skipped, the inner condition is not evaluated.
考试时,在每一层只追踪被选中的分支。如果包含内层 IF 的外层分支被跳过,内层条件就不会被求值。
What does this code display?
下面的代码显示什么?
x ← 10 y ← 4 IF (x ≥ 10) { IF (y ≥ 5) { DISPLAY("A") } ELSE { DISPLAY("B") } } ELSE { DISPLAY("C") }
x ≥ 10is true, so enter the outerIFbranch.y ≥ 5is false, so enter the innerELSEbranch.- The code displays
B, followed by a space. The outerELSEis skipped.
x ≥ 10为真,因此进入外层IF分支。y ≥ 5为假,因此进入内层ELSE分支。- 代码显示
B,后面带一个空格。外层ELSE被跳过。
A common wrong answer is C because the inner condition is false. But C belongs to the outer ELSE, which runs only when x ≥ 10 is false.
常见错误是因为内层条件为假而回答 C。但 C 属于外层 ELSE,只有 x ≥ 10 为假时才会执行。
In the example, A is displayed only when both conditions are true. The two ways that fails have different results: a false outer condition displays C, while a true outer condition and a false inner condition display B. Replacing the nesting with one IF using AND and one ELSE would not preserve both results.
在例题中,只有两个条件都为真时才会显示 A。未满足这一要求的两种情况会产生不同结果:外层条件为假时显示 C,外层条件为真但内层条件为假时显示 B。如果用一个含 AND 的 IF 和一个 ELSE 替换嵌套结构,就无法保留这两种不同结果。
Iteration
迭代(iteration)
- Iteration repeats part of an algorithm a specified number of times or until a condition is met. (AAP-2.J.1)
- Iteration changes the sequential flow of control by repeating statements zero or more times. (AAP-2.K.1)
REPEAT n TIMESexecutes its block exactlyntimes. (AAP-2.K.2)REPEAT UNTIL(condition)repeats its block until the Boolean condition is true. (AAP-2.K.3)- The condition is checked before each pass. If it is initially true, the body runs zero times. If it never becomes true, the loop is infinite. (AAP-2.K.4, AAP-2.K.5)
- 迭代重复算法的一部分,重复指定次数或直到满足某个条件。 (AAP-2.J.1)
- 迭代通过将语句重复零次或多次,改变顺序控制流(flow of control)。 (AAP-2.K.1)
REPEAT n TIMES将其语句块恰好执行n次。 (AAP-2.K.2)REPEAT UNTIL(condition)重复其语句块,直到布尔条件(Boolean condition)为真。 (AAP-2.K.3)- 每次执行前都会检查条件。若条件最初为真,循环体(loop body)执行零次;若条件永远不为真,就会出现无限循环(infinite loop)。 (AAP-2.K.4, AAP-2.K.5)
Describe and write repetition
描述和编写重复过程
An algorithm can describe iteration without a programming language: “Start at 0. Add 2 until the value is at least 6.” Check the value before each addition. A fixed-count loop instead says how many times to repeat, such as “Add 2 three times.”
算法可以不用编程语言来描述迭代:“从 0 开始,不断加 2,直到数值至少为 6。”每次加法前先检查数值。固定次数循环则说明要重复多少次,例如“加 2 三次”。
For exam questions, trace the variables and any displayed values in order. For REPEAT UNTIL, check the stopping condition before entering the body and again before each later pass.
考试中,要按顺序追踪变量和显示的值。对于 REPEAT UNTIL,进入循环体前先检查停止条件,此后每次执行前也要检查。
What does this code display, and what is the final value of x?
这段代码显示什么?x 的最终值是多少?
x ← 0 REPEAT 2 TIMES { x ← x + 1 DISPLAY(x) } REPEAT UNTIL(x ≥ 5) { x ← x + 2 DISPLAY(x) }
- The fixed-count loop runs twice. It displays
1and then2;xis now2. 2 ≥ 5is false, so the second loop runs. It changesxto4and displays4.4 ≥ 5is false, so the body runs again. It changesxto6and displays6.6 ≥ 5is true, so the loop stops. The answer is1 2 4 6, with a space after each displayed value; the final value ofxis6.
- 固定次数循环执行两次,依次显示
1和2;此时x为2。 2 ≥ 5为假,因此第二个循环执行。它将x改为4并显示4。4 ≥ 5为假,因此循环体再次执行。它将x改为6并显示6。6 ≥ 5为真,因此循环停止。答案是1 2 4 6,每个显示的值后都有一个空格;x的最终值为6。
REPEAT UNTIL always runs once. If its condition is already true, it runs zero times because the condition is checked first. Also, the loop continues while the condition is false, not while it is true.
REPEAT UNTIL 总会执行一次。如果条件一开始就为真,循环会执行零次,因为条件先被检查。另外,条件为假时循环继续,而不是条件为真时继续。
x ≥ 5 with x = 5 causes an infinite loop: the second loop starts at 2 and then reaches 4, 6, and so on, never 5.
x ≥ 5 改为 x = 5,就会产生无限循环:第二个循环从 2 开始,之后依次达到 4、6 等值,永远不会达到 5。
Developing Algorithms
开发算法
- Different algorithms can solve the same problem and produce the same result or side effects. Similar-looking algorithms can instead behave differently. (AAP-2.L.1, AAP-2.L.2, AAP-2.L.5)
- Some conditionals and Boolean expressions can be written equivalently as each other. Check their results for every relevant case. (AAP-2.L.3, AAP-2.L.4)
- Create algorithms from an idea, or combine and modify existing algorithms. (AAP-2.M.1)
- Useful building blocks find a maximum or minimum, calculate a sum or average, test divisibility, and find a robot's path through a maze. (AAP-2.M.2)
- Reusing correct algorithms can reduce development time and testing, and make errors easier to identify. (AAP-2.M.3)
- 不同的算法(algorithm)可以解决同一问题,并产生相同的结果或副作用(side effect)。看起来相似的算法也可能表现不同。(AAP-2.L.1, AAP-2.L.2, AAP-2.L.5)
- 有些条件语句(conditional)和布尔表达式(Boolean expression)可以相互等价地改写。要检查所有相关情况下的结果。(AAP-2.L.3, AAP-2.L.4)
- 可以从一个想法创建算法,也可以组合或修改现有算法。(AAP-2.M.1)
- 常用的构件包括求最大值或最小值、计算总和或平均值、判断整除,以及确定机器人穿过迷宫的路径。(AAP-2.M.2)
- 复用正确的算法可以减少开发时间和测试工作,并使错误更容易定位。(AAP-2.M.3)
Compare algorithms
比较算法
Exam pattern: trace each algorithm on the same input, then compare both its final results and its side effects, such as displayed values. One matching test is useful, but it does not prove two algorithms behave the same for every valid input.
考试常见模式:对同一输入分别追踪每个算法,然后比较最终结果和副作用,例如显示的值。一个测试结果相同很有帮助,但不能证明两个算法对每个有效输入都表现相同。
A conditional that assigns true when a test is true and false otherwise can be replaced by assigning the test's Boolean value directly. The reverse replacement also works if both branches assign the corresponding value.
如果条件语句在判断为真时赋值 true、否则赋值 false,就可以改为直接赋值该判断的布尔值。反过来,只要两个分支分别赋予对应的值,也可以用条件语句替换布尔赋值。
Build from known algorithms
利用已知算法构建
To find a maximum among numbers, keep a candidate and replace it when a larger number is found. For a minimum, replace it when a smaller number is found. Add the numbers for a sum; divide the sum by the count for an average. For a nonnegative integer and a positive divisor, a remainder of zero means the integer is evenly divisible by that divisor.
求一组数的最大值时,保留一个候选值,遇到更大的数就替换。求最小值时,遇到更小的数就替换。将数字相加得到总和,再用总和除以个数得到平均值。对于非负整数和正除数,余数为零表示该整数能被除数整除。
For a robot maze, determine a path through open squares and account for the robot's direction. For example, if three open squares form a row and the robot starts at one end facing the other, two forward moves reach the far end. A blocked or off-grid move terminates the program.
对于机器人迷宫,要确定一条经过开放格子的路径,并考虑机器人的朝向。例如,三个开放格子排成一行,机器人从一端出发并朝向另一端时,向前移动两次即可到达远端。试图移入受阻格子或网格外会使程序终止。
Both algorithms process the same nonempty list of nonnegative integers. Compare their final values and side effects for this list.
两个算法处理同一个由非负整数组成的非空列表。比较它们针对该列表的最终值和副作用。
Algorithm A:
算法 A:
numbers ← [4, 7, 8] total ← 0 maximum ← numbers[1] evenCount ← 0 FOR EACH item IN numbers { total ← total + item IF(item > maximum) { maximum ← item } isEven ← (item MOD 2 = 0) IF(isEven) { evenCount ← evenCount + 1 } } average ← total / LENGTH(numbers)
Algorithm B:
算法 B:
numbers ← [4, 7, 8] total ← 0 maximum ← numbers[1] evenCount ← 0 i ← 1 REPEAT UNTIL(i > LENGTH(numbers)) { item ← numbers[i] total ← total + item IF(item > maximum) { maximum ← item } IF(item MOD 2 = 0) { isEven ← true } ELSE { isEven ← false } IF(isEven) { evenCount ← evenCount + 1 } i ← i + 1 } average ← total / LENGTH(numbers)
- Both visit 4, 7, and 8 in order. The totals are 4, 11, and 19. The maximum ends at 8.
- In both algorithms,
isEvenis true for 4 and 8, and false for 7. The direct Boolean assignment in A matches the conditional assignment in B. The finalevenCountis 2. - The average is
19 / 3. Neither algorithm displays anything. Their computed summary values match, although B also uses the indexi. - Answer: for this input, both produce total 19, maximum 8, even count 2, and average
19 / 3, with no display side effect.
- 两个算法都依次访问 4、7、8。总和依次为 4、11、19,最终最大值为 8。
- 在两个算法中,4 和 8 对应的
isEven为真,7 对应的为假。A 中的直接布尔赋值与 B 中的条件赋值等价。最终evenCount为 2。 - 平均值为
19 / 3。两个算法都没有显示任何内容。它们计算出的汇总值相同,不过 B 还使用了索引i。 - 答案:对于该输入,两者都得到总和 19、最大值 8、偶数个数 2、平均值
19 / 3,且都没有显示方面的副作用。
Lists
列表
- Lists use 1-based indexing. Read or assign an element with
aList[i]. (AAP-2.N.1) INSERTshifts elements right,APPENDadds at the end,REMOVEshifts later elements left, andLENGTHreturns the current number of elements. (AAP-2.N.1)- List procedures follow the syntax rules of the programming language. (AAP-2.N.2)
- Iteration can traverse all or part of a list.
FOR EACHvisits values in order from first to last. (AAP-2.O.1, AAP-2.O.2, AAP-2.O.3) - Common list algorithms find a minimum or maximum, compute a sum or average, or search in order for a value. Trace both the list and the variables. (AAP-2.O.4, AAP-2.O.5)
- 列表(list)的索引从 1 开始。用
aList[i]读取元素或给元素赋值。(AAP-2.N.1) INSERT将元素右移,APPEND在末尾添加元素,REMOVE将后续元素左移,LENGTH返回当前元素个数。(AAP-2.N.1)- 列表过程必须遵守所用编程语言的语法规则。(AAP-2.N.2)
- 迭代(iteration)可以遍历列表的全部或部分元素。
FOR EACH按从首到尾的顺序访问各值。(AAP-2.O.1、AAP-2.O.2、AAP-2.O.3) - 常见列表算法包括求最小值或最大值、求和或平均值,以及按顺序查找目标值。做题时同时追踪列表和变量。(AAP-2.O.4、AAP-2.O.5)
Access and change elements
访问和修改元素
x ← aList[i] assigns the element at index i to x. aList[i] ← x replaces that element. aList[i] ← aList[j] assigns the value at j to the element at i; it does not remove the element at j.
x ← aList[i] 将索引 i 处的元素赋给 x。aList[i] ← x 替换该元素。aList[i] ← aList[j] 将索引 j 处的值赋给索引 i 处的元素;它不会删除索引 j 处的元素。
After an insertion or removal, trace the new indices before the next operation. An index below 1 or above the current length causes an error and terminates the program.
插入或删除后,先确认新的索引,再执行下一步。索引小于 1 或大于当前长度会导致错误并终止程序。
Traverse and search
遍历与查找
A complete traversal accesses every element; a partial traversal accesses only some. In FOR EACH item IN aList, item takes each value in order, and the block runs once for each value. For a sum, start at 0 and add each value. For a maximum or minimum, start with the first value of a nonempty list and compare each value. For an average, divide the sum by the length of a nonempty list.
完整遍历(complete traversal)访问每个元素;部分遍历(partial traversal)只访问其中一部分。在 FOR EACH item IN aList 中,item 按顺序取得每个值,代码块对每个值执行一次。求和时,从 0 开始并加上每个值。求最大值或最小值时,用非空列表的第一个值初始化,再比较各值。求平均值时,将总和除以非空列表的长度。
A linear search, also called a sequential search, checks values in order until it finds the target or has checked the whole list. For example, the following code sets found and, when found, leaves i at the first matching index. It also handles an empty list.
线性查找(linear search),也叫顺序查找(sequential search),按顺序检查各值,直到找到目标或检查完整个列表。例如,下面的代码设置 found;找到目标时,i 停留在第一个匹配的索引。它也能处理空列表。
aList ← [9, 6, 9, 7] target ← 6 i ← 1 found ← false REPEAT UNTIL(found OR i > LENGTH(aList)) { IF(aList[i] = target) { found ← true } ELSE { i ← i + 1 } }
Here the search checks 9 and then 6, so found is true and i is 2. It does not access the remaining elements.
这里查找先检查 9,再检查 6,因此 found 为 true,i 为 2。它不会访问剩余元素。
Trace the list operations, then determine the displayed sum and maximum.
追踪列表操作,再求显示的总和与最大值。
items ← [4, 9, 2] x ← items[2] items[1] ← x INSERT(items, 2, 6) REMOVE(items, 3) APPEND(items, 7) items[3] ← items[1] sum ← 0 maximum ← items[1] FOR EACH value IN items { sum ← sum + value IF(value > maximum) { maximum ← value } } DISPLAY(sum) DISPLAY(maximum)
xbecomes 9. Replacing the first element gives[9, 9, 2].- Inserting 6 at index 2 gives
[9, 6, 9, 2]. Removing index 3 gives[9, 6, 2]. - Appending 7 and then assigning the first value to index 3 gives
[9, 6, 9, 7]. - The traversal adds all four values: the sum is 31. The maximum remains 9. The answer is
31 9, with a space after each displayed value.
x变为 9。替换第一个元素后,列表为[9, 9, 2]。- 在索引 2 插入 6,得到
[9, 6, 9, 2]。删除索引 3 的元素,得到[9, 6, 2]。 - 在末尾添加 7,再将第一个值赋给索引 3,得到
[9, 6, 9, 7]。 - 遍历时加上全部四个值,总和为 31,最大值保持为 9。答案是
31 9,每个显示的值后面都有一个空格。
INSERT(items, 2, 6) as a replacement. It adds an element instead, shifting the old index 2 and later elements right. Likewise, removal shifts later elements left. Recalculate indices after each change.
INSERT(items, 2, 6) 当作替换。它实际上会添加元素,并将原索引 2 及之后的元素右移。同样,删除会将后续元素左移。每次修改后都要重新确定索引。
FOR EACH block runs zero times. Do not initialize a maximum with items[1] or divide by the length for an average unless the list is nonempty. For a nonempty list, initializing a maximum to 0 can also be wrong if every value is negative.
FOR EACH 代码块执行零次。只有在列表非空时,才能用 items[1] 初始化最大值,或在求平均值时除以列表长度。对于非空列表,如果所有值都是负数,将最大值初始化为 0 也可能得到错误结果。
Binary Search
二分查找(binary search)
- Binary search checks the middle of a sorted data set and repeatedly eliminates about half of the remaining elements until the value is found or none remain. (AAP-2.P.1)
- The data must be sorted before binary search is used. (AAP-2.P.2)
- Binary search is often more efficient than sequential or linear search on sorted data. (AAP-2.P.3)
- On the exam, trace each middle-element check to count the iterations. Specific implementations are outside the course and exam scope. (AAP-2.P.1)
- 二分查找检查已排序数据集中间的元素,并反复排除剩余元素中约一半,直到找到目标值或没有剩余元素。(AAP-2.P.1)
- 使用二分查找前,数据必须按顺序排列。(AAP-2.P.2)
- 对于已排序的数据,二分查找通常比顺序查找或线性查找(sequential or linear search)更高效。(AAP-2.P.3)
- 考试中,逐次追踪对中间元素的检查,以计算迭代(iteration)次数。具体实现不属于课程和考试范围。(AAP-2.P.1)
How to trace a search
如何追踪查找过程
For data sorted from smallest to largest, compare the target with the middle element. If they are equal, stop. If the target is smaller, continue in the lower part. If it is larger, continue in the upper part. If no elements remain, the target is not present.
对于从小到大排序的数据,将目标值与中间元素比较。相等则停止;目标值较小则继续查找较低的一部分;目标值较大则继续查找较高的一部分。如果没有剩余元素,说明目标值不存在。
Count one iteration for each middle element checked. When an even number of elements remains, either of the two middle elements can be chosen. Follow the choice specified in the question, since it can affect the count.
每检查一个中间元素,计为一次迭代。当剩余元素个数为偶数时,可以选择两个中间元素中的任意一个。要遵循题目指定的选择方式,因为选择可能影响次数。
Search for 18 in the sorted data set [2, 5, 8, 11, 14, 17, 18]. How many middle-element checks are needed?
在已排序的数据集 [2, 5, 8, 11, 14, 17, 18] 中查找 18。需要检查多少次中间元素?
- Check 11, the middle element. Since 18 is larger, continue with [14, 17, 18].
- Check 17. Since 18 is larger, continue with [18].
- Check 18. It matches the target, so stop. Answer: 3 checks, or 3 iterations.
- 检查中间元素 11。因为 18 较大,继续查找 [14, 17, 18]。
- 检查 17。因为 18 较大,继续查找 [18]。
- 检查 18。它与目标值相同,因此停止。答案:检查 3 次,即迭代 3 次。
Calling Procedures
调用过程
- A procedure is a named group of instructions. It may have parameters and return values, and may be called a method or function. (AAP-3.A.1, AAP-3.A.2)
- Parameters are input variables. Arguments give them values in order when a procedure is called. A call can have zero or more arguments. (AAP-3.A.3, AAP-3.A.5)
- A call runs the procedure before execution continues. The last statement or a
RETURNsends control back to the call. (AAP-3.A.4) RETURN(expression)returns a value and exits the procedure. Assign a returned value withresult ← procName(arg1, arg2). (AAP-3.A.7, AAP-3.A.8)DISPLAY(expression)displays a value followed by a space.INPUT()accepts and returns a user value. (AAP-3.A.6, AAP-3.A.9)
- 过程(procedure)是一组有名称的指令,可以有参数和返回值;它也可能被称为方法(method)或函数(function)。(AAP-3.A.1, AAP-3.A.2)
- 参数(parameter)是输入变量。调用过程时,实参(argument)按顺序为参数提供值。一次调用可以有零个或多个实参。(AAP-3.A.3, AAP-3.A.5)
- 调用会先执行过程,再继续执行原来的代码。执行完最后一条语句或执行
RETURN后,控制流返回调用处。(AAP-3.A.4) RETURN(expression)返回一个值并退出过程。用result ← procName(arg1, arg2)将返回值赋给变量。(AAP-3.A.7, AAP-3.A.8)DISPLAY(expression)显示一个值,后面带一个空格。INPUT()接收并返回用户输入的值。(AAP-3.A.6, AAP-3.A.9)
Calls and control flow
调用与控制流
Write a call using the procedure name and its arguments in parentheses. The first argument supplies the first parameter, the second supplies the second, and so on. Calling existing procedures lets a program reuse instructions without repeating them.
编写调用时,先写过程名,再在括号中写实参。第一个实参对应第一个参数,第二个实参对应第二个参数,依此类推。调用已有过程可以复用指令,不必重复编写。
On the exam, trace a call by matching arguments to parameters, running the procedure, and then continuing from the call. If the call is part of an assignment, the returned value is assigned before the next statement runs.
考试中追踪调用时,先把实参与参数对应起来,再执行过程,然后从调用处继续。如果调用是赋值语句的一部分,返回值会先被赋值,再执行下一条语句。
Returning and displaying
返回与显示
RETURN immediately exits the procedure and provides a value to the call. It does not display that value. DISPLAY shows a value followed by a space. INPUT() takes no arguments and returns the user's input.
RETURN 会立即退出过程,并向调用处提供一个值。它不会显示该值。DISPLAY 显示一个值,后面带一个空格。INPUT() 不需要实参,并返回用户输入的值。
The user enters 4. What does this program display?
用户输入 4。这个程序显示什么?
PROCEDURE adjust(value, limit) { IF(value > limit) { RETURN(limit) } RETURN(value + 1) } number ← INPUT() result ← adjust(number, 3) DISPLAY(result) DISPLAY(number)
INPUT()returns4, sonumberbecomes4.- The call assigns
4tovalueand3tolimit. 4 > 3is true, soRETURN(limit)returns3immediately. The laterRETURNdoes not run.- The returned value is assigned to
result. The two calls toDISPLAYshow3and4, each followed by a space. The answer is3 4with a trailing space.
INPUT()返回4,因此number变为4。- 调用把
4赋给value,把3赋给limit。 4 > 3为真,所以RETURN(limit)立即返回3。后面的RETURN不会执行。- 返回值被赋给
result。两次DISPLAY分别显示3和4,每个值后都有一个空格。答案是3 4,末尾还有一个空格。
The wrong answer is that RETURN(3) displays 3. It returns the value to the call; only a later DISPLAY shows it. Also, statements after an executed RETURN in that procedure do not run.
常见错误是认为 RETURN(3) 会显示 3。它只是把值返回给调用处;只有之后的 DISPLAY 才会显示该值。另外,过程中的 RETURN 一旦执行,其后的语句就不会执行。
Argument order can change the result. In the example, adjust(4, 3) returns 3, but adjust(3, 4) returns 4: the condition is false, so the second RETURN runs. Trace the parameter values before choosing a branch.
实参顺序可能改变结果。在例题中,adjust(4, 3) 返回 3,而 adjust(3, 4) 返回 4:条件为假,因此执行第二个 RETURN。判断分支前,先追踪各参数的值。
Developing Procedures
开发过程
- Procedural abstraction names a process, so a caller needs to know what it does, not how it works. (AAP-3.B.1)
- Procedures can solve smaller subproblems. Dividing a program into separate subprograms is modularity. (AAP-3.B.2, AAP-3.B.3)
- Extract shared behavior into a procedure instead of duplicating code. Parameters let it work with a range of arguments. (AAP-3.B.4, AAP-3.B.5)
- Procedures can improve readability. Their internals can change without notifying users if their behavior is preserved. (AAP-3.B.6, AAP-3.B.7)
- A procedure has a block of statements and can take zero or more arguments. A procedure may return a value;
RETURNimmediately exits it. (AAP-3.C.1, AAP-3.C.2)
- 过程抽象(procedural abstraction)为一个过程命名,调用者只需知道它做什么,不必知道它如何实现。(AAP-3.B.1)
- 过程(procedure)可以解决较小的子问题。将程序划分为独立子程序称为模块化(modularity)。(AAP-3.B.2, AAP-3.B.3)
- 将共同功能提取到过程中,避免重复代码。参数(parameter)让过程能处理一系列不同的实参(argument)。(AAP-3.B.4, AAP-3.B.5)
- 过程可以提高代码可读性。只要过程的行为保持不变,就可以更改其内部实现而无须通知用户。(AAP-3.B.6, AAP-3.B.7)
- 过程包含语句块,可以接收零个或多个实参。过程可以返回一个值;
RETURN会立即退出过程。(AAP-3.C.1, AAP-3.C.2)
Build and reuse procedures
构建并复用过程
Break a large problem into smaller tasks, then write a procedure for each task. A descriptive procedure name makes the larger solution easier to read. A caller can use the procedure based on what it does without reading its internal statements.
将大问题拆分成较小的任务,然后为每个任务编写过程。描述性强的过程名称能让整体解决方案更易读。调用者可以根据过程的功能使用它,而不必阅读其内部语句。
When tasks share the same process but use different values, write the process once with parameters. Each call supplies arguments. On an exam, look for the procedure that preserves the intended behavior for all the given inputs, not just one example.
当多个任务使用相同的处理过程但数值不同时,可以编写一次带参数的过程。每次调用提供不同的实参。考试时,要选择对所有给定输入都能保持预期行为的过程,而不是只适用于一个例子的过程。
Define and return
定义过程与返回值
A procedure definition names the procedure, lists any parameters, and contains its statements. A procedure can have no parameters and need not return a value. If it uses RETURN(expression), the expression's value is returned to the caller immediately. Statements after that return are not executed during that call.
过程定义给过程命名、列出参数(如果有),并包含其语句。过程可以没有参数,也不一定返回值。如果使用 RETURN(expression),表达式的值会立即返回给调用者。该次调用中,返回语句之后的语句不会执行。
A program needs the difference between two values when the first is greater; otherwise it needs 0. Define one procedure and trace these calls.
一个程序需要在第一个值较大时求两个值的差,否则得到 0。定义一个过程,并跟踪以下调用。
PROCEDURE NonnegativeDifference(a, b) { IF(a > b) { RETURN(a - b) } RETURN(0) } x ← NonnegativeDifference(9, 4) y ← NonnegativeDifference(2, 7) z ← NonnegativeDifference(5, 5) DISPLAY(x) DISPLAY(y) DISPLAY(z)
- For the first call,
ais 9 andbis 4. The condition is true, so the procedure returns 5 immediately. - For the second call, 2 is not greater than 7. The procedure skips the first return and returns 0.
- For the third call, the values are equal, so the condition is also false and the procedure returns 0.
- The answer is 5, 0, 0, each followed by a space. The same procedure handles all three calls without duplicating its logic.
- 第一次调用时,
a为 9,b为 4。条件为真,因此过程立即返回 5。 - 第二次调用时,2 不大于 7。过程跳过第一个返回语句,返回 0。
- 第三次调用时,两个值相等,因此条件也为假,过程返回 0。
- 答案依次为 5、0、0,每个值后都有一个空格。同一个过程处理了三次调用,无须重复编写逻辑。
A common wrong answer says the first call above returns 0 because the last statement is RETURN(0). It returns 5: the earlier RETURN exits the procedure immediately, so the last statement is not reached.
常见错误答案认为上面的第一次调用返回 0,因为最后一条语句是 RETURN(0)。实际返回 5:前面的 RETURN 会立即退出过程,因此不会执行最后一条语句。
The procedure hides its comparison and subtraction behind a name. Its internals could be changed to improve efficiency or use less storage without notifying callers, provided it still returns the same intended result for each input. Changing the equality case to return a different value would not preserve that behavior.
该过程用一个名称隐藏了内部的比较和减法。可以更改其内部实现以提高效率或减少存储空间,无须通知调用者,但前提是对每个输入仍返回相同的预期结果。如果将两值相等时的返回值改为其他值,就没有保持原有行为。
Libraries
库
- A software library contains procedures that can be used to create new programs. (AAP-3.D.1)
- Existing code can come from internal or external sources, including libraries and previously written code. (AAP-3.D.2)
- Libraries simplify the creation of complex programs. (AAP-3.D.3)
- An application program interface (API) specifies how a library’s procedures behave and can be used. (AAP-3.D.4)
- Read API or library documentation to understand what procedures do and how to use them. (AAP-3.D.5)
- 软件库(software library)包含可用于创建新程序的过程(procedure)。(AAP-3.D.1)
- 现有代码可以来自内部或外部来源,包括库和以前编写的代码。(AAP-3.D.2)
- 库可以简化复杂程序的创建。(AAP-3.D.3)
- 应用程序接口(application program interface,API)规定库中的过程如何运行以及如何使用。(AAP-3.D.4)
- 阅读 API 或库文档,了解过程的功能和使用方法。(AAP-3.D.5)
Selecting existing code
选择现有代码
To select a library procedure, match the task to its documented behavior. Check what arguments it takes and what result it returns. Reusing suitable code lets a programmer focus on other parts of the program.
选择库过程时,要将任务需求与文档中描述的行为相匹配。检查过程需要哪些参数以及返回什么结果。复用合适的代码可以让程序员专注于程序的其他部分。
Exam pattern: given a task and procedure descriptions, choose the procedure whose behavior fits the task, then use it as documented. A library is the collection of procedures; its API specifies how those procedures behave and can be used.
考试常见题型:根据任务和过程说明,选择行为符合需求的过程,再按文档使用。库是过程的集合;其 API 规定这些过程如何运行以及如何使用。
A library documents CountItems(items) as returning the number of items in a list, including 0 for an empty list. It documents SumItems(items) as returning the sum of a list’s numbers. A program needs the number of scores, not their sum.
某库的文档说明,CountItems(items) 返回列表中的元素个数,空列表返回 0;SumItems(items) 返回列表中数值的总和。一个程序需要分数的个数,而不是总和。
scores ← [2, 3, 4] result ← CountItems(scores) DISPLAY(result)
- The task asks for a count, so choose
CountItems, notSumItems. - Pass
scoresas the list argument. It contains three items. - The procedure returns 3, which is assigned to
result. The answer is3, displayed with a trailing space.
- 任务要求元素个数,因此选择
CountItems,而不是SumItems。 - 将
scores作为列表实参传入。该列表有三个元素。 - 过程返回 3,并赋值给
result。答案是显示3,其后有一个空格。
SumItems because it works on the same list is wrong: its documented result is the sum, not the number of items. Match the procedure’s behavior to the task, not just its input.
SumItems 也能处理同一个列表就选择它,是错误的:文档说明它返回总和,而不是元素个数。要根据过程的行为是否符合任务来选择,不能只看输入。
CountItems returns 0. Do not assume every procedure handles every input in the same way. Consult its documentation before relying on an edge case.
CountItems 的文档规定返回 0。不要假设每个过程都以相同方式处理所有输入。遇到边界情况(edge case)时,应先查阅文档再确定其行为。
Random Values
随机值
RANDOM(a, b)returns a random integer fromathroughb, inclusive. (AAP-3.E.1)- Each integer in that range is equally likely. (AAP-3.E.1)
- To evaluate an expression, list the possible random integers and apply the remaining operations to each. (AAP-3.E.1)
- Different executions of a program using random values may produce different results, but they can also produce the same result. (AAP-3.E.2)
RANDOM(a, b)返回从a到b的一个随机整数,包含两个端点。 (AAP-3.E.1)- 该范围内每个整数出现的可能性相同。 (AAP-3.E.1)
- 求表达式的可能结果时,列出可能的随机整数,再对每个整数执行其余运算。 (AAP-3.E.1)
- 使用随机值的程序在不同次运行时可能产生不同结果,也可能产生相同结果。 (AAP-3.E.2)
Writing and evaluating expressions
编写并求表达式的结果
To generate integers from 1 through 3, use RANDOM(1, 3). Its possible results are 1, 2, and 3. On an exam, check both endpoints before applying any arithmetic outside the call.
要生成 1 到 3 的整数,可以使用 RANDOM(1, 3)。它的可能结果是 1、2 和 3。考试时,先检查两个端点,再执行调用之外的算术运算。
To write an expression for a range, choose the desired inclusive bounds directly. For example, RANDOM(5, 7) generates 5, 6, or 7.
编写生成某个范围内整数的表达式时,可以直接选用所需的包含端点的上下界。例如,RANDOM(5, 7) 生成 5、6 或 7。
What values can this code display, and how likely is each value?
这段代码可能显示哪些值?每个值出现的可能性如何?
value ← RANDOM(1, 3) + 4 DISPLAY(value)
RANDOM(1, 3)can return 1, 2, or 3, each with probability 1/3.- Add 4 to each result. The possible values of
valueare 5, 6, and 7. DISPLAYshows the value followed by a space. The answer is 5, 6, or 7, each with probability 1/3.
RANDOM(1, 3)可以返回 1、2 或 3,每个结果的概率都是 1/3。- 将每个结果加 4,得到
value的可能值 5、6 和 7。 DISPLAY显示该值,后面带一个空格。答案是 5、6 或 7,每个值的概率都是 1/3。
RANDOM(1, 3) can return only 1 or 2. Both endpoints are included, so 3 is possible too. It cannot return a decimal such as 1.5.
RANDOM(1, 3) 只能返回 1 或 2。两个端点都包含在内,所以 3 也是可能结果。它不能返回 1.5 这样的小数。
RANDOM, not necessarily to results after another operation. For RANDOM(1, 3) MOD 2, both 1 and 3 produce 1, while only 2 produces 0. So 1 has probability 2/3 and 0 has probability 1/3.
RANDOM 返回的整数,但后续运算的结果不一定等可能。对于 RANDOM(1, 3) MOD 2,1 和 3 都产生 1,只有 2 产生 0。因此,结果为 1 的概率是 2/3,结果为 0 的概率是 1/3。
Simulations
模拟
- A simulation is an abstraction of a complex object or phenomenon for a specific purpose. It uses varying values to represent a changing state. (AAP-3.F.1, AAP-3.F.2)
- Simulations mimic events to support inferences and investigation without some real-world constraints. They are especially useful when experiments are impractical, such as when they are too dangerous or expensive. (AAP-3.F.3, AAP-3.F.6)
- Building a simulation involves removing details or simplifying functionality. Choices about what to include or exclude can introduce bias. (AAP-3.F.4, AAP-3.F.5)
- Simulations help formulate and refine hypotheses about the phenomena being studied. (AAP-3.F.7)
- Random number generators can represent real-world variability. On the exam, compare the model’s choices and outcomes with the real-world situation. (AAP-3.F.8)
- 模拟(simulation)是为特定目的对复杂对象或现象进行的抽象(abstraction),它用变化的数值表示不断变化的状态。 (AAP-3.F.1, AAP-3.F.2)
- 模拟模仿事件,帮助人们在不受某些现实约束的情况下进行探究和推断。当实验不切实际,例如过于危险或昂贵时,模拟尤其有用。 (AAP-3.F.3, AAP-3.F.6)
- 构建模拟时需要去除细节或简化功能。选择包含或排除哪些内容可能引入偏差(bias)。 (AAP-3.F.4, AAP-3.F.5)
- 模拟有助于提出和完善关于所研究现象的假设(hypothesis)。 (AAP-3.F.7)
- 随机数生成器(random number generator)可以表示现实世界中的变化。考试时要比较模型的选择和结果与现实情况。 (AAP-3.F.8)
Representing a phenomenon
表示现象
A computer simulation keeps selected values for a phenomenon and changes them as the simulation runs. Its purpose determines which details matter. For example, a model of rainy days might track whether each day is rainy while omitting temperature and location.
计算机模拟保存现象中选定的数值,并在运行过程中改变这些数值。模拟目的决定了哪些细节重要。例如,雨天模型可以记录每天是否下雨,同时省略温度和地点。
Comparing a model with reality
比较模型与现实
A simulation can help investigate a hypothesis without performing an experiment that is too large, small, fast, slow, expensive, or dangerous. Its results support inferences about the modeled situation, but omitted or simplified factors may make those inferences less useful for the real situation.
模拟可以帮助研究假设,而不必实际进行规模过大或过小、速度过快或过慢、过于昂贵或危险的实验。模拟结果可以支持对模型所表示情况的推断,但被省略或简化的因素可能降低这些推断对现实情况的参考价值。
A model treats each of 10 days as rainy when a random integer from 1 through 4 is 1. Suppose the random values are 1, 2, 4, 1, 3, 2, 1, 4, 2, 3. What does the program display, and what is one limitation?
一个模型用 1 到 4 的随机整数模拟 10 天:数值为 1 时表示当天是雨天。假设生成的随机数依次为 1、2、4、1、3、2、1、4、2、3。程序显示什么?这个模型有什么局限?
rainyDays ← 0 REPEAT 10 TIMES { draw ← RANDOM(1, 4) IF (draw = 1) { rainyDays ← rainyDays + 1 } } DISPLAY(rainyDays)
- Each call to
RANDOM(1, 4)can return 1, 2, 3, or 4 with equal likelihood. In this model, 1 represents a rainy day. - The value 1 occurs three times in the given sequence, so
rainyDaysbecomes 3. - The program displays 3 followed by a space. The model omits factors such as location and relationships between consecutive days, so its result need not reflect a real location.
- 每次调用
RANDOM(1, 4)都可能以相同的概率返回 1、2、3 或 4。在此模型中,1 表示雨天。 - 给定序列中,1 出现了三次,因此
rainyDays变为 3。 - 程序显示 3,后面跟一个空格。模型省略了地点、连续几天之间的关系等因素,因此结果不一定反映真实地点的情况。
Algorithmic Efficiency
算法效率
- A problem describes a task; an instance includes a specific input. Decision problems ask yes/no questions, while optimization problems seek the best solution. (AAP-4.A.1, AAP-4.A.2)
- Efficiency estimates computational resources used as input size changes. It can be determined through mathematical reasoning or informally measured by counting statement executions. (AAP-4.A.3, AAP-4.A.4, AAP-4.A.5)
- Different correct algorithms for the same problem can have different efficiencies. (AAP-4.A.6)
- Constant, linear, square, cube, and other polynomial efficiencies are considered reasonable; exponential and factorial efficiencies are examples of unreasonable efficiency. (AAP-4.A.7)
- When no efficient algorithm is available, an approximate solution may be sought. A heuristic may be useful when finding an optimal solution is impractical, but it does not guarantee an optimal result. (AAP-4.A.8, AAP-4.A.9)
- 问题(problem)描述一项任务;问题实例(instance)还包含具体输入。判定问题(decision problem)要求回答是或否,优化问题(optimization problem)则要寻找最优解。(AAP-4.A.1, AAP-4.A.2)
- 效率(efficiency)估计输入规模变化时算法使用的计算资源。可以通过数学推理确定效率,也可以通过统计语句执行次数进行非正式衡量。(AAP-4.A.3, AAP-4.A.4, AAP-4.A.5)
- 解决同一问题的不同正确算法,效率可能不同。(AAP-4.A.6)
- 常数、线性、平方、立方等多项式效率被视为合理;指数和阶乘效率是不合理效率的例子。(AAP-4.A.7)
- 当没有高效算法时,可以寻求近似解。寻找最优解不切实际时,启发式方法(heuristic)可能有用,但它不保证得到最优结果。(AAP-4.A.8, AAP-4.A.9)
Problems and efficiency
问题与效率
Sorting is a problem. Sorting the list [2, 3, 1, 7] is an instance because the input is specified. “Is there a path from A to B?” is a decision problem. “What is the shortest path from A to B?” is an optimization problem.
排序是一个问题。对列表 [2, 3, 1, 7] 排序是一个问题实例,因为输入已确定。“从 A 到 B 是否有路径?”是判定问题。“从 A 到 B 的最短路径是什么?”是优化问题。
To compare algorithms, consider how their resource use changes with input size. One informal measure is the number of times a chosen statement executes. Formal mathematical analysis can determine efficiency, but Big-O and formal reasoning with formulas are outside AP CSP scope.
比较算法时,要考虑计算资源用量如何随输入规模变化。一种非正式的衡量方法是统计选定语句的执行次数。正式的数学分析可以确定效率,但 Big-O 和使用数学公式进行正式推理不属于 AP CSP 考查范围。
Reasonable time and heuristics
合理时间与启发式方法
For the exam, classify polynomial efficiencies, including constant and linear, as reasonable. Exponential and factorial efficiencies are examples of unreasonable time. Some problems have no efficient algorithm, so an approximate solution may be more practical than waiting for an optimal one.
考试中,常数、线性以及其他多项式效率归为合理时间。指数和阶乘效率是不合理时间的例子。有些问题没有高效算法,因此寻求近似解可能比等待最优解更实际。
A heuristic is an approach that may produce a useful solution without guaranteeing the best one. Consider it when a method guaranteed to find the optimal solution is impractical.
启发式方法是一种可能给出有用解、但不保证得到最优解的方法。当保证找到最优解的方法不切实际时,可以考虑使用启发式方法。
Both algorithms display the sum of the values in numbers. For the input [2, 3, 1, 7], compare how many times total ← total + item executes.
两个算法都显示 numbers 中所有数值的总和。对于输入 [2, 3, 1, 7],比较 total ← total + item 的执行次数。
Algorithm A:
算法 A:
numbers ← [2, 3, 1, 7] total ← 0 FOR EACH item IN numbers { total ← total + item } DISPLAY(total)
Algorithm B:
算法 B:
numbers ← [2, 3, 1, 7] total ← 0 REPEAT LENGTH(numbers) TIMES { total ← 0 FOR EACH item IN numbers { total ← total + item } } DISPLAY(total)
- Algorithm A adds each of the four values once, so the chosen statement executes 4 times. Its displayed sum is 13.
- Algorithm B recomputes the sum four times, resetting
totalbefore each pass. The chosen statement executes 4 times per pass, or 16 times. Its displayed sum is also 13. - For a list of size
n, the counts arenandn * n. They are linear and square, respectively, so both are considered reasonable. Answer: A uses fewer additions for this input; both are correct.
- 算法 A 将四个数各加一次,所以选定语句执行 4 次。它显示的总和是 13。
- 算法 B 重新计算总和四次,每次遍历前都将
total重置。选定语句每次执行 4 次,共执行 16 次。它显示的总和也是 13。 - 对于长度为
n的列表,执行次数分别是n和n * n。它们分别是线性和平方效率,因此都被视为合理。答案:对于此输入,A 的加法次数更少;两个算法都正确。
Undecidable Problems
不可判定问题
A decision problem asks for a yes-or-no answer. It is decidable if an algorithm can give the correct answer for every valid input. (AAP-4.B.1)
An undecidable problem has no algorithm that always gives a correct yes-or-no answer. (AAP-4.B.2)
Some instances of an undecidable problem may be solvable by an algorithm, even though no algorithm solves all instances. (AAP-4.B.3)
Exam pattern: distinguish solving a particular instance from solving every instance.
判定问题(decision problem)要求回答“是”或“否”。如果存在一个算法,能对每个有效输入给出正确答案,该问题就是可判定的(decidable)。(AAP-4.B.1)
不可判定问题(undecidable problem)不存在能始终给出正确“是”或“否”答案的算法。(AAP-4.B.2)
不可判定问题的某些实例(instance)可能可以用算法解决,但不存在能解决所有实例的算法。(AAP-4.B.3)
考试常见考法:区分解决某一个实例与解决所有实例。
What does “all inputs” mean?
“所有输入”是什么意思?
A decision problem describes a question and its valid inputs. To decide it, one algorithm must finish and give the correct yes-or-no answer for every valid input. For example, an algorithm can decide whether a number is even.
判定问题描述一个问题及其有效输入。要判定该问题,必须存在一个算法,对每个有效输入都能结束并给出正确的“是”或“否”答案。例如,可以用算法判定一个数是否为偶数。
For an undecidable problem, no algorithm meets that requirement for every instance. This does not mean that every individual instance is impossible to solve.
对于不可判定问题,不存在能对每个实例都满足这一要求的算法。这并不意味着每个单独的实例都无法解决。
Problem E asks whether a nonnegative integer is even. The code below solves E. Problem P is given as undecidable, but an algorithm correctly answers one particular instance of P. What can we conclude?
问题 E 询问一个非负整数是否为偶数。下面的代码解决问题 E。已知问题 P 不可判定,但有一个算法能正确回答 P 的某个特定实例。可以得出什么结论?
n ← INPUT() IF (n MOD 2 = 0) { DISPLAY("yes") } ELSE { DISPLAY("no") }
- For every valid input to E, the remainder after division by 2 is either 0 or 1. The code displays the correct answer and finishes.
- Because this one algorithm works for every valid input, E is decidable.
- Solving one instance of P does not give an algorithm that solves every instance. Answer: E is decidable, and P can still be undecidable.
- 对于 E 的每个有效输入,除以 2 的余数不是 0 就是 1。代码会显示正确答案并结束。
- 因为这一个算法对每个有效输入都有效,所以 E 是可判定的。
- 解决 P 的一个实例,并不意味着有算法能解决它的所有实例。答案:E 是可判定的,而 P 仍然可以是不可判定的。
Wrong answer: “One instance of P can be solved, so P is decidable.” Decidability requires an algorithm that correctly answers every valid instance, not just one.
错误答案:“P 的一个实例可以解决,所以 P 是可判定的。”可判定性要求存在一个能正确回答每个有效实例的算法,而不只是一个实例。
Do not confuse undecidability with a long running time. A decidable problem has an algorithm that answers every valid input correctly, although that algorithm may not run in a reasonable amount of time. An undecidable problem has no such algorithm for all instances. Determining whether a given problem is undecidable is outside the course and exam scope.
不要把不可判定性与运行时间长混为一谈。可判定问题存在能正确回答每个有效输入的算法,但该算法可能无法在合理时间内运行。不可判定问题则不存在能解决所有实例的这种算法。判断一个给定问题是否不可判定不在课程和考试范围内。
Trace the pseudocode one line at a time
逐行追踪伪代码
Unit 3 MCQ Patterns That Show Up Every Year
单元 3 每年都会出现的选择题套路
Questions often ask you to trace pseudocode, compare algorithms, or choose an abstraction for a scenario. Track values and control flow carefully, and use the exam reference sheet for list indices and procedure behavior.
选择题经常要求你追踪伪代码(pseudocode)、比较算法(algorithm),或为情境选择合适的抽象(abstraction)。仔细记录数值和控制流程,并参考考试参考表确认列表索引及过程的行为。
Flashcards, Click to Flip
闪卡(点击翻面)
Unit 3, Practice Quiz
单元 3:练习小测
x ← 17 y ← x MOD 5 x ← x / 5 DISPLAY(y + x)
n ← 7 IF(n > 5) { IF(n MOD 2 = 0) { DISPLAY(1) } ELSE { DISPLAY(2) } } ELSE { IF(n = 5) { DISPLAY(3) } ELSE { DISPLAY(4) } }
values ← [3, 8, 2] INSERT(values, 2, 5) REMOVE(values, 3) total ← 0 FOR EACH item IN values { IF(item ≥ 3) { total ← total + item } } DISPLAY(total)
PROCEDURE adjust(n) { IF(n > 3) { RETURN(n * 2) } RETURN(n + 1) } a ← adjust(4) b ← adjust(2) DISPLAY(a + b)
AP-Style Practice Problems
AP 风格练习题
Ready for more? Try the 15-question practice set to reinforce code tracing and algorithm reasoning.
准备好继续练习了吗?完成 15 道题的练习集,巩固代码追踪和算法推理。
鼎睿学苑 · Dingrui Scholars
AP Computer Science Principles, Unit 3: Algorithms and Programming · 2026 Edition
AP 计算机科学原理,单元 3:算法与编程 · 2026 版