← 学习库 Think Python (2e) · 中英对照 目录

Chapter 13  Case study: data structure selection 第 13 章 案例研究:数据结构选择

本页译自 Think Python 2e(Allen B. Downey)· Chapter 13 Case study: data structure selection。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。

13.1 Word frequency analysis 13.1 词频分析

As usual, you should at least attempt the following exercises before you read my solutions.

照老规矩,先自己动手做下面这些习题,再来看我的解答。

Exercise 1

习题 1

Write a program that reads a file, breaks each line into words, strips whitespace and punctuation from the words, and converts them to lowercase.

写一个程序,读入一个文件,把每一行拆成单词,去掉单词两端的空白和标点,并转成小写。

Hint: The string module provides strings named string005, which contains space, tab, newline, etc., and string006 which contains the punctuation characters. Let’s see if we can make Python swear:

提示:string 模块里有两个字符串,string008 包含空格、制表符、换行符等,string009 包含各种标点字符。来看看能不能让 Python 骂两句脏话:
string010

Also, you might consider using the string methods strip, string0 and string013.

另外,可以考虑用字符串方法 stripstring0 和 string016。

Exercise 2

习题 2

Go to Project Gutenberg (string017) and download your favorite out-of-copyright book in plain text format.

去古腾堡计划(string018)下载一本你喜欢的、已进入公有领域的书,取纯文本格式。

Modify your program from the previous exercise to read the book you downloaded, skip over the header information at the beginning of the file, and process the rest of the words as before.

改写上一题的程序,让它读入你下载的这本书,跳过文件开头的头部信息,其余部分照前面的办法逐词处理。

Then modify the program to count the total number of words in the book, and the number of times each word is used.

再改写程序,统计全书的总词数,以及每个词出现的次数。

Print the number of different words used in the book. Compare different books by different authors, written in different eras. Which author uses the most extensive vocabulary?

打印书中用到的不同单词的数量。拿不同年代、不同作者的书比一比:哪位作者的词汇量最大?

Exercise 3

习题 3

Modify the program from the previous exercise to print the 20 most frequently-used words in the book.

改写上一题的程序,打印书中出现频率最高的 20 个词。

Exercise 4

习题 4

Modify the previous program to read a word list (see Section 9.1) and then print all the words in the book that are not in the word list. How many of them are typos? How many of them are common words that should be in the word list, and how many of them are really obscure?

改写上一题的程序,读入一份词表(见 9.1 节),然后打印书中所有不在词表里的单词。其中有多少是拼写错误?有多少是本收进词表的常用词?又有多少是真正的生僻词?

13.2 Random numbers 13.2 随机数

Given the same inputs, most computer programs generate the same outputs every time, so they are said to be deterministic. Determinism is usually a good thing, since we expect the same calculation to yield the same result. For some applications, though, we want the computer to be unpredictable. Games are an obvious example, but there are more.

给同样的输入,多数程序每次都给出同样的输出,这种程序叫作确定性的(deterministic)。确定性通常是好事:同样的计算本该得到同样的结果。不过有些应用场景里,我们偏偏希望计算机不可预测。游戏是最明显的例子,但远不止游戏。

Making a program truly nondeterministic turns out to be not so easy, but there are ways to make it at least seem nondeterministic. One of them is to use algorithms that generate pseudorandom numbers. Pseudorandom numbers are not truly random because they are generated by a deterministic computation, but just by looking at the numbers it is all but impossible to distinguish them from random.

要让程序真正做到非确定性并不容易,但至少可以让它看起来非确定。办法之一是用生成伪随机(pseudorandom)数的算法。伪随机数并非真随机,因为它们由确定性的计算得出;可只看这些数字,几乎没法把它们和真随机数区分开。

The string module provides functions that generate pseudorandom numbers (which I will simply call “random” from here on).

string 模块提供了生成伪随机数的函数(下文我就简称「随机数」)。

The function string returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0). Each time you call string, you get the next number in a long series. To see a sample, run this loop:

string 函数返回一个 0.0 到 1.0 之间的随机浮点数(含 0.0,不含 1.0)。每次调用 string,就取到这个长序列里的下一个数。想看看效果,跑这个循环:
string025

The function string0 takes parameters low and low0 and returns an integer between low and low0 (including both).

string0 函数接受形参 lowlow0,返回 lowlow0 之间的一个整数(两端都含)。
string036

To choose an element from a sequence at random, you can use string:

要从一个序列里随机取一个元素,可以用 string
string039

The string module also provides functions to generate random values from continuous distributions including Gaussian, exponential, gamma, and a few more.

string 模块还提供了按连续分布取随机值的函数,包括高斯分布、指数分布、伽马分布等等。

Exercise 5

习题 5

Write a function named string042 that takes a histogram as defined in Section 11.1 and returns a random value from the histogram, chosen with probability in proportion to frequency. For example, for this histogram:

写一个名为 string043 的函数,参数是 11.1 节定义的那种直方图,返回直方图中的一个随机值,被选中的概率与频次成正比。例如对这个直方图:
string044

your function should return low with probability 2/3 and low with probability 1/3.

你的函数应以 2/3 的概率返回 low,以 1/3 的概率返回 low

13.3 Word histogram 13.3 词直方图

You should attempt the previous exercises before you go on. You can download my solution from string049. You will also need string050.

继续往下读之前,先自己做一遍前面的习题。我的解答可以从 string051 下载,还需要 string052。

Here is a program that reads a file and builds a histogram of the words in the file:

下面这个程序读入一个文件,并为文件中的单词建一个直方图:
string053

This program reads string05, which contains the text of Emma by Jane Austen.

这个程序读入 string05,里面是简·奥斯汀的小说《爱玛》(Emma)全文。

string056 loops through the lines of the file, passing them one at a time to string057. The histogram low0 is being used as an accumulator.

string059 遍历文件的每一行,一行一行交给 string060。直方图 low0 在这里充当累加器。

string062 uses the string method string0 to replace hyphens with spaces before using strip to break the line into a list of strings. It traverses the list of words and uses strip and strip to remove punctuation and convert to lower case. (It is a shorthand to say that strings are “converted;” remember that string are immutable, so methods like strip and strip return new strings.)

string069 先用字符串方法 string0 把连字符换成空格,再用 strip 把这一行拆成字符串列表。接着遍历单词列表,用 stripstrip 去掉标点并转小写。(说字符串被「转换」只是图省事的说法;别忘了字符串是不可变的,stripstrip 这类方法返回的是新字符串。)

Finally, string076 updates the histogram by creating a new item or incrementing an existing one.

最后,string077 更新直方图:新建一个条目,或给已有条目加一。

To count the total number of words in the file, we can add up the frequencies in the histogram:

要统计文件里的总词数,把直方图中的频次加起来就行:
string078

The number of different words is just the number of items in the dictionary:

不同单词的数量,就是字典里条目的个数:
string079

Here is some code to print the results:

下面这几行代码打印结果:
string080

And the results:

结果如下:
string081

13.4 Most common words 13.4 最常见的词

To find the most common words, we can apply the DSU pattern; string082 takes a histogram and returns a list of word-frequency tuples, sorted in reverse order by frequency:

要找出最常见的词,可以套用 DSU 模式;string083 接受一个直方图,返回「词-频次」元组的列表,按频次逆序排好:
string084

Here is a loop that prints the ten most common words:

下面这个循环打印最常见的十个词:
string085

And here are the results from Emma:

下面是《爱玛》的结果:
string086

13.5 Optional parameters 13.5 可选形参

We have seen built-in functions and methods that take a variable number of arguments. It is possible to write user-defined functions with optional arguments, too. For example, here is a function that prints the most common words in a histogram

前面见过一些内置函数和方法,实参个数可多可少。自己写的函数也能带可选实参。例如下面这个函数,打印直方图里最常见的词:
string087

The first parameter is required; the second is optional. The default value of low is 10.

第一个形参是必需的,第二个是可选的。low默认值(default value)是 10。

If you only provide one argument:

如果只给一个实参:
string090

low gets the default value. If you provide two arguments:

low 就取默认值。如果给两个实参:
string093

low gets the value of the argument instead. In other words, the optional argument overrides the default value.

low 取的就是这个实参的值。换句话说,可选实参覆盖(override)了默认值。

If a function has both required and optional parameters, all the required parameters have to come first, followed by the optional ones.

如果一个函数既有必需形参又有可选形参,必需的必须全排在前面,可选的排在后面。

13.6 Dictionary subtraction 13.6 字典减法

Finding the words from the book that are not in the word list from string096 is a problem you might recognize as set subtraction; that is, we want to find all the words from one set (the words in the book) that are not in another set (the words in the list).

找出书里那些不在 string097 词表中的单词,你大概能认出这是集合减法:从一个集合(书里的词)中找出所有不属于另一个集合(词表里的词)的元素。

string09 takes dictionaries d1 and d1 and returns a new dictionary that contains all the keys from d1 that are not in d1. Since we don’t really care about the values, we set them all to None.

string10 接受两个字典 d1d1,返回一个新字典,包含 d1 中所有不在 d1 里的键。反正值用不上,就统统设成 None。
string108

To find the words in the book that are not in string109, we can use string110 to build a histogram for string111, and then subtract:

要找出书里不在 string112 中的词,可以先用 string113 为 string114 建一个直方图,然后做减法:
string115

Here are some of the results from Emma:

下面是《爱玛》的部分结果:
string116

Some of these words are names and possessives. Others, like “rencontre,” are no longer in common use. But a few are common words that should really be in the list!

其中一些是人名和所有格形式;另一些,比如 “rencontre”,早已不再常用。可也有几个确实是常用词,本该收进词表才对!

Exercise 6

习题 6

Python provides a data structure called low that provides many common set operations. Read the documentation at string118 and write a program that uses set subtraction to find words in the book that are not in the word list. Solution: string119.

Python 提供了一种叫 low(集合)的数据结构,支持许多常见的集合运算。读一读 string121 的文档,然后写一个程序,用集合减法找出书中不在词表里的单词。解答:string122。

13.7 Random words 13.7 随机词

To choose a random word from the histogram, the simplest algorithm is to build a list with multiple copies of each word, according to the observed frequency, and then choose from the list:

要从直方图里随机取一个词,最简单的算法是:按观察到的频次,把每个词复制相应份数放进一个列表,再从列表里随机取:
string123

The expression string124 creates a list with low0 copies of the string low0. The string method is similar to string except that the argument is a sequence.

表达式 string129 生成一个列表,里面是字符串 low0 的 low0 份副本。string 方法和 string 类似,区别是它的实参是一个序列。

Exercise 7

习题 7

This algorithm works, but it is not very efficient; each time you choose a random word, it rebuilds the list, which is as big as the original book. An obvious improvement is to build the list once and then make multiple selections, but the list is still big.

这个算法能用,但效率不高:每取一个随机词都要重建一遍列表,而列表的规模跟整本书一样大。一个明显的改进是只建一次列表,然后反复取值,可列表还是那么大。

An alternative is:

另一种做法是:
  1. Use low0 to get a list of the words in the book.
  2. Build a list that contains the cumulative sum of the word frequencies (see Exercise 3). The last item in this list is the total number of words in the book, n.
  3. Choose a random number from 1 to n. Use a bisection search (See Exercise 11) to find the index where the random number would be inserted in the cumulative sum.
  4. Use the index to find the corresponding word in the word list.
  1. low0 取出书中所有单词的列表。
  2. 建一个列表,存放词频的累积和(见习题 3)。这个列表的最后一项就是全书的总词数 n
  3. 从 1 到 n 取一个随机数。用二分查找(见习题 11)找出这个随机数插入累积和序列时所在的索引。
  4. 用这个索引到单词列表里找出对应的词。

Write a program that uses this algorithm to choose a random word from the book. Solution: string136.

写一个程序,用这个算法从书里随机取词。解答:string137。

13.8 Markov analysis 13.8 马尔可夫分析

If you choose words from the book at random, you can get a sense of the vocabulary, you probably won’t get a sentence:

从书里随机取词,能看出词汇的大致面貌,但基本凑不出一个句子:
string138

A series of random words seldom makes sense because there is no relationship between successive words. For example, in a real sentence you would expect an article like “the” to be followed by an adjective or a noun, and probably not a verb or adverb.

一串随机词很少讲得通,因为相邻的词之间没有任何关联。比如在真句子里,像 “the” 这样的冠词后面该跟形容词或名词,一般不会跟动词或副词。

One way to measure these kinds of relationships is Markov analysis, which characterizes, for a given sequence of words, the probability of the word that comes next. For example, the song Eric, the Half a Bee begins:

衡量这类关联的一个办法是马尔可夫分析(Markov analysis):给定一串词,刻画出下一个词的出现概率。比如歌曲《Eric, the Half a Bee》的开头:

Half a bee, philosophically,
Must, ipso facto, half not be.
But half the bee has got to be
Vis a vis, its entity. D’you see?

But can a bee be said to be
Or not to be an entire bee
When half the bee is not a bee
Due to some ancient injury?

半只蜜蜂,从哲学上讲,
依此推论,必有一半不成其为蜂。
可那存在的半只蜜蜂,
终究要面对它自己的本体。明白吗?

但一只蜜蜂究竟能不能说是
或者不是一只完整的蜜蜂,
当半只蜜蜂已算不得蜜蜂,
只因某处古老的旧伤?

In this text, the phrase “half the” is always followed by the word “bee,” but the phrase “the bee” might be followed by either “has” or “is”.

在这段文字里,短语 “half the” 后面总是跟着 “bee”,而短语 “the bee” 后面既可能跟 “has”,也可能跟 “is”。

The result of Markov analysis is a mapping from each prefix (like “half the” and “the bee”) to all possible suffixes (like “has” and “is”).

马尔可夫分析的结果,是一个从每个前缀(prefix,如 “half the”、“the bee”)到所有可能后缀(suffix,如 “has”、“is”)的映射。

Given this mapping, you can generate a random text by starting with any prefix and choosing at random from the possible suffixes. Next, you can combine the end of the prefix and the new suffix to form the next prefix, and repeat.

有了这个映射,就能生成随机文本:从任意前缀出发,从可能的后缀里随机挑一个;再把前缀的尾部和这个新后缀拼起来,构成下一个前缀,如此反复。

For example, if you start with the prefix “Half a,” then the next word has to be “bee,” because the prefix only appears once in the text. The next prefix is “a bee,” so the next suffix might be “philosophically,” “be” or “due.”

例如从前缀 “Half a” 出发,下一个词只能是 “bee”,因为这个前缀在文中只出现过一次。接下来的前缀是 “a bee”,于是下一个后缀可能是 “philosophically”、“be” 或 “due”。

In this example the length of the prefix is always two, but you can do Markov analysis with any prefix length. The length of the prefix is called the “order” of the analysis.

这个例子里前缀长度一律是 2,但马尔可夫分析可以用任意前缀长度。前缀的长度称为该分析的「阶」(order)。

Exercise 8

习题 8

Markov analysis:

马尔可夫分析:
  1. Write a program to read a text from a file and perform Markov analysis. The result should be a dictionary that maps from prefixes to a collection of possible suffixes. The collection might be a list, tuple, or dictionary; it is up to you to make an appropriate choice. You can test your program with prefix length two, but you should write the program in a way that makes it easy to try other lengths.
  2. Add a function to the previous program to generate random text based on the Markov analysis. Here is an example from Emma with prefix length 2:
  3. Once your program is working, you might want to try a mash-up: if you analyze text from two or more books, the random text you generate will blend the vocabulary and phrases from the sources in interesting ways.
  1. 写一个程序,从文件读入一段文本并做马尔可夫分析。结果应是一个字典,把前缀映射到一组可能的后缀。这组后缀可以用列表、元组或字典表示,怎么选合适由你决定。测试时可以用前缀长度 2,但程序要写得便于改用其他长度。
  2. 给上面的程序加一个函数,基于马尔可夫分析生成随机文本。下面是取自《爱玛》、前缀长度为 2 的一个例子:
  3. 程序跑通之后,不妨试试「混搭」:如果分析两本或更多书的文本,生成的随机文本会以有趣的方式把各来源的词汇和短语揉在一起。

He was very clever, be it sweetness or be angry, ashamed or only amused, at such a stroke. She had never thought of Hannah till you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself.

他非常聪明,无论是甜言蜜语还是发怒,是羞愧还是只觉得好笑,面对这样一记打击。她从没想到过汉娜,直到你从来就不是为我准备的?「我不会讲漂亮话,爱玛:」他很快就自己把话全打断了。(机器生成的随机文本,语法勉强通顺、语义似通非通,中文只作示意。)

For this example, I left the punctuation attached to the words. The result is almost syntactically correct, but not quite. Semantically, it almost makes sense, but not quite.

这个例子里我把标点留在了词上。结果在语法上差不多对,但不完全对;在语义上差不多说得通,但也不完全说得通。

What happens if you increase the prefix length? Does the random text make more sense?

把前缀长度加大会怎样?生成的随机文本更讲得通了吗?

Credit: This case study is based on an example from Kernighan and Pike, The Practice of Programming, Addison-Wesley, 1999.

致谢:本案例研究取材于 Kernighan 与 Pike 所著《程序设计实践》(The Practice of Programming),Addison-Wesley,1999。

You should attempt this exercise before you go on; then you can can download my solution from string139. You will also need string140.

继续往下读之前先做这道题;之后可以从 string141 下载我的解答,还需要 string142。

13.9 Data structures 13.9 数据结构

Using Markov analysis to generate random text is fun, but there is also a point to this exercise: data structure selection. In your solution to the previous exercises, you had to choose:

用马尔可夫分析生成随机文本很好玩,但这道题还有正经的用意:数据结构的选择。在解前面那些题时,你必须做几个决定:

Ok, the last one is easy; the only mapping type we have seen is a dictionary, so it is the natural choice.

好吧,最后一个简单:我们见过的映射类型只有字典,那它就是顺理成章的选择。

For the prefixes, the most obvious options are string, list of strings, or tuple of strings. For the suffixes, one option is a list; another is a histogram (dictionary).

前缀的表示,最容易想到的是字符串、字符串列表或字符串元组。后缀的表示,一种是列表,另一种是直方图(字典)。

How should you choose? The first step is to think about the operations you will need to implement for each data structure. For the prefixes, we need to be able to remove words from the beginning and add to the end. For example, if the current prefix is “Half a,” and the next word is “bee,” you need to be able to form the next prefix, “a bee.”

该怎么选?第一步是想清楚每种数据结构上需要实现哪些操作。对前缀,我们要能从头部删词、从尾部加词。例如当前前缀是 “Half a”,下一个词是 “bee”,那就得能拼出下一个前缀 “a bee”。

Your first choice might be a list, since it is easy to add and remove elements, but we also need to be able to use the prefixes as keys in a dictionary, so that rules out lists. With tuples, you can’t append or remove, but you can use the addition operator to form a new tuple:

你的第一反应可能是列表,因为增删元素方便;但我们还得把前缀当字典的键用,这就把列表排除了。元组不能追加或删除,可以用加法运算符拼出一个新元组:
string143

strip takes a tuple of words, string, and a string, low0, and forms a new tuple that has all the words in string except the first, and low0 added to the end.

strip 接受一个词元组 string 和一个字符串 low0,构造出一个新元组:去掉 string 的第一个词,并把 low0 加到末尾。

For the collection of suffixes, the operations we need to perform include adding a new suffix (or increasing the frequency of an existing one), and choosing a random suffix.

对后缀集合,需要的操作包括:加入一个新后缀(或给已有后缀的频次加一),以及随机取一个后缀。

Adding a new suffix is equally easy for the list implementation or the histogram. Choosing a random element from a list is easy; choosing from a histogram is harder to do efficiently (see Exercise 7).

加入新后缀这件事,用列表实现和用直方图实现一样容易。从列表里随机取元素很简单;从直方图里高效地随机取就麻烦些(见习题 7)。

So far we have been talking mostly about ease of implementation, but there are other factors to consider in choosing data structures. One is run time. Sometimes there is a theoretical reason to expect one data structure to be faster than other; for example, I mentioned that the d1 operator is faster for dictionaries than for lists, at least when the number of elements is large.

到这里谈的多半是实现的难易,可选数据结构还得考虑别的因素。一个是运行时间。有时理论上就能判断某种数据结构更快;比如前面提过,d1 运算符用在字典上比用在列表上快——至少在元素很多的时候是这样。

But often you don’t know ahead of time which implementation will be faster. One option is to implement both of them and see which is better. This approach is called benchmarking. A practical alternative is to choose the data structure that is easiest to implement, and then see if it is fast enough for the intended application. If so, there is no need to go on. If not, there are tools, like the string1 module, that can identify the places in a program that take the most time.

但很多时候事先并不知道哪种实现更快。一个办法是两种都实现,看哪个更好,这叫基准测试(benchmarking,性能测试)。更实用的替代做法是:先选最容易实现的那种,再看它对目标应用是否够快。够快就到此为止;不够快的话,还有 string1 模块这类工具,能找出程序里最耗时的地方。

The other factor to consider is storage space. For example, using a histogram for the collection of suffixes might take less space because you only have to store each word once, no matter how many times it appears in the text. In some cases, saving space can also make your program run faster, and in the extreme, your program might not run at all if you run out of memory. But for many applications, space is a secondary consideration after run time.

另一个要考虑的因素是存储空间。例如用直方图存后缀集合可能更省空间,因为每个词只存一次,无论它在文中出现多少遍。省空间有时也能让程序跑得更快;极端情况下,内存耗尽程序根本跑不起来。不过对多数应用来说,空间是排在运行时间之后的次要考虑。

One final thought: in this discussion, I have implied that we should use one data structure for both analysis and generation. But since these are separate phases, it would also be possible to use one structure for analysis and then convert to another structure for generation. This would be a net win if the time saved during generation exceeded the time spent in conversion.

最后一点想法:上面的讨论暗含一个前提——分析和生成用同一种数据结构。但既然这是两个独立阶段,也完全可以分析时用一种结构,生成前再转成另一种。只要生成阶段省下的时间超过转换花掉的时间,这笔账就是划算的。

13.10 Debugging 13.10 调试

When you are debugging a program, and especially if you are working on a hard bug, there are four things to try:

调试程序时,尤其是在啃一个难缠的缺陷时,有四件事可以试:
reading:
Examine your code, read it back to yourself, and check that it says what you meant to say.
running:
Experiment by making changes and running different versions. Often if you display the right thing at the right place in the program, the problem becomes obvious, but sometimes you have to spend some time to build scaffolding.
ruminating:
Take some time to think! What kind of error is it: syntax, runtime, semantic? What information can you get from the error messages, or from the output of the program? What kind of error could cause the problem you’re seeing? What did you change last, before the problem appeared?
retreating:
At some point, the best thing to do is back off, undoing recent changes, until you get back to a program that works and that you understand. Then you can start rebuilding.
reading 读代码:
仔细看你的代码,念给自己听,核对它说的是不是你想说的。
running 跑程序:
动手改一改,跑不同的版本试试。常常只要在程序里合适的位置打印出合适的东西,问题就一目了然;但有时得花点工夫搭脚手架。
ruminating 静下来想:
花点时间思考!这是哪类错误:语法错误、运行时错误还是语义错误?从错误消息或程序输出里能得到什么信息?什么样的错误会导致你看到的现象?问题出现前,你最后改动了什么?
retreating 往回退:
到了某个时候,最好的办法是后退,把最近的改动撤掉,退回到一个能跑、你也看得懂的版本,然后重新往上搭。

Beginning programmers sometimes get stuck on one of these activities and forget the others. Each activity comes with its own failure mode.

初学者常常死磕其中一件,忘了还有别的三件。而每一件都有自己的失效方式。

For example, reading your code might help if the problem is a typographical error, but not if the problem is a conceptual misunderstanding. If you don’t understand what your program does, you can read it 100 times and never see the error, because the error is in your head.

比如说,如果问题是笔误,读代码有用;如果问题是概念上想错了,读代码就没用。要是你根本没搞懂自己的程序在干什么,读上一百遍也看不出错误在哪,因为错误长在你脑子里。

Running experiments can help, especially if you run small, simple tests. But if you run experiments without thinking or reading your code, you might fall into a pattern I call “random walk programming,” which is the process of making random changes until the program does the right thing. Needless to say, random walk programming can take a long time.

做实验有用,尤其是跑小而简单的测试。但如果只顾实验,不思考、不读代码,就容易掉进我叫作「随机游走式编程」的套路——胡乱改动,直到程序碰巧对了为止。不用说,随机游走式编程可以拖上很久。

You have to take time to think. Debugging is like an experimental science. You should have at least one hypothesis about what the problem is. If there are two or more possibilities, try to think of a test that would eliminate one of them.

你必须花时间思考。调试像一门实验科学:对问题出在哪,至少要有一个假设。如果有两种或更多可能,就想个测试出来,好排掉其中一种。

Taking a break helps with the thinking. So does talking. If you explain the problem to someone else (or even yourself), you will sometimes find the answer before you finish asking the question.

歇一会儿有助于思考,说出来也一样。把问题讲给别人(甚至讲给自己)听,有时话还没问完,答案就自己冒出来了。

But even the best debugging techniques will fail if there are too many errors, or if the code you are trying to fix is too big and complicated. Sometimes the best option is to retreat, simplifying the program until you get to something that works and that you understand.

不过错误太多,或者要修的代码又大又乱时,再好的调试技巧也会失效。这时最好的选择往往是往回退:不断简化程序,直到退到一个能跑、你也看得懂的东西。

Beginning programmers are often reluctant to retreat because they can’t stand to delete a line of code (even if it’s wrong). If it makes you feel better, copy your program into another file before you start stripping it down. Then you can paste the pieces back in a little bit at a time.

初学者常不情愿往回退,因为舍不得删掉哪怕一行代码(就算那行是错的)。要是这样能让你心里舒服些:动手精简之前,先把程序复制到另一个文件里,之后再一点一点把各块粘回来。

Finding a hard bug requires reading, running, ruminating, and sometimes retreating. If you get stuck on one of these activities, try the others.

揪出一个难缠的缺陷,需要读代码、跑程序、静下来想,有时还得往回退。要是在某一件上卡住了,就换另几件试试。

13.11 Glossary 13.11 术语表

deterministic:
Pertaining to a program that does the same thing each time it runs, given the same inputs.
pseudorandom:
Pertaining to a sequence of numbers that appear to be random, but are generated by a deterministic program.
default value:
The value given to an optional parameter if no argument is provided.
override:
To replace a default value with an argument.
benchmarking:
The process of choosing between data structures by implementing alternatives and testing them on a sample of the possible inputs.
deterministic 确定性的:
用于形容这样的程序:给定同样的输入,每次运行都做同样的事。
pseudorandom 伪随机:
用于形容这样的数列:看上去是随机的,实际由确定性的程序生成。
default value 默认值:
未提供实参时,可选形参取到的值。
override 覆盖:
用实参取代默认值。
benchmarking 基准测试(性能测试):
在几种数据结构之间做选择的过程:把备选方案都实现出来,用一批可能的输入样本测试它们。

13.12 Exercises 13.12 习题

Exercise 9

习题 9

The “rank” of a word is its position in a list of words sorted by frequency: the most common word has rank 1, the second most common has rank 2, etc.

一个词的「排名」(rank)是它在按频次排序的词表中的位置:最常见的词排名 1,次常见的排名 2,依此类推。

Zipf’s law describes a relationship between the ranks and frequencies of words in natural languages (string158). Specifically, it predicts that the frequency, f, of the word with rank r is:

齐普夫定律(Zipf’s law)描述了自然语言中词的排名与频次之间的关系(string159)。具体地说,它预测排名为 r 的词的频次 f 为:

f = c rs

f = c rs

where s and c are parameters that depend on the language and the text. If you take the logarithm of both sides of this equation, you get:

其中 sc 是两个参数,取值取决于语言和具体文本。对这个等式两边取对数,得到:

logf = logcs logr

logf = logcs logr

So if you plot log f versus log r, you should get a straight line with slope −s and intercept log c.

所以,若以 log r 为横轴、log f 为纵轴作图,应当得到一条直线,斜率为 −s,截距为 log c

Write a program that reads a text from a file, counts word frequencies, and prints one line for each word, in descending order of frequency, with log f and log r. Use the graphing program of your choice to plot the results and check whether they form a straight line. Can you estimate the value of s?

写一个程序,从文件读入文本,统计词频,然后按频次降序为每个词打印一行,附上 log f 和 log r。用你顺手的绘图程序把结果画出来,看看是不是一条直线。你能估出 s 的值吗?

Solution: string160. To make the plots, you might have to install matplotlib (see string161).

解答:string162。要画图,可能得先装 matplotlib(见 string163)。