forked from carfly/thinkpython-cn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbook.tex
23796 lines (18227 loc) · 810 KB
/
book.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% LaTeX source for ``Think Python: How to Think Like a Computer Scientist''
% Copyright (c) 2012 Allen B. Downey.
% License: Creative Commons Attribution-NonCommercial 3.0 Unported License.
% http://creativecommons.org/licenses/by-nc/3.0/
%
%\documentclass[10pt,b5paper]{book}
\documentclass[10pt]{book}
\usepackage[width=5.5in,height=8.5in,
hmarginratio=3:2,vmarginratio=1:1]{geometry}
% for some of these packages, you might have to install
% texlive-latex-extra (in Ubuntu)
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{mathpazo}
\usepackage{url}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amsthm}
%\usepackage{amssymb}
\usepackage{exercise} % texlive-latex-extra
\usepackage{makeidx}
\usepackage{setspace}
\usepackage{hevea}
\usepackage{upquote}
\usepackage{appendix}
\usepackage[bookmarks]{hyperref}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% XeTex Part %%
\usepackage{ifxetex}
\ifxetex
\usepackage{fontspec}
\usepackage{xeCJK}
\XeTeXlinebreaklocale "zh"
\setCJKmainfont{AR PL UMing CN}
\else
\usepackage{CJKutf8}
\fi
%脚注每页单独编号
\usepackage[perpage]{footmisc}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\title{Think Python}
\author{Allen B. Downey}
\newcommand{\thetitle}{Think Python: How to Think Like a Computer Scientist}
\newcommand{\theversion}{2.0.5}
\newcommand{\thedate}{December 2012}
% these styles get translated in CSS for the HTML version
\newstyle{a:link}{color:black;}
\newstyle{p+p}{margin-top:1em;margin-bottom:1em}
\newstyle{img}{border:0px}
% change the arrows
\setlinkstext
{\imgsrc[ALT="Previous"]{back.png}}
{\imgsrc[ALT="Up"]{up.png}}
{\imgsrc[ALT="Next"]{next.png}}
\makeindex
\newif\ifplastex
\plastexfalse
\begin{document}
\ifxetex
\else
\begin{CJK}{UTF8}{gbsn}
\fi
\frontmatter
% PLASTEX ONLY
\ifplastex
\usepackage{localdef}
\maketitle
\newcount\anchorcnt
\newcommand*{\Anchor}[1]{%
\@bsphack%
\Hy@GlobalStepCount\anchorcnt%
\edef\@currentHref{anchor.\the\anchorcnt}%
\Hy@raisedlink{\hyper@anchorstart{\@currentHref}\hyper@anchorend}%
\M@gettitle{}\label{#1}%
\@esphack%
}
\else
% skip the following for plastex
\newtheorem{exercise}{Exercise}[chapter]
% LATEXONLY
\input{latexonly}
\begin{latexonly}
\renewcommand{\blankpage}{\thispagestyle{empty} \quad \newpage}
%\blankpage
%\blankpage
% TITLE PAGES FOR LATEX VERSION
%-half title--------------------------------------------------
\thispagestyle{empty}
\begin{flushright}
\vspace*{2.0in}
\begin{spacing}{3}
{\huge Think Python}\\
{\Large How to Think Like a Computer Scientist \\
如何像计算机科学家一样思考}
\end{spacing}
\vspace{0.25in}
Version \theversion
\thedate
\vfill
\end{flushright}
%--verso------------------------------------------------------
\blankpage
\blankpage
%\clearemptydoublepage
%\pagebreak
%\thispagestyle{empty}
%\vspace*{6in}
%--title page--------------------------------------------------
\pagebreak
\thispagestyle{empty}
\begin{flushright}
\vspace*{2.0in}
\begin{spacing}{3}
{\huge Think Python}\\
{\Large How to Think Like a Computer Scientist}
\end{spacing}
\vspace{0.25in}
Version \theversion
\thedate
\vspace{1in}
{\Large
Allen Downey\\
}
\vspace{0.5in}
{\Large Green Tea Press}
{\small Needham, Massachusetts}
%\includegraphics[width=1in]{figs/logo1.pdf}
\vfill
\end{flushright}
%--copyright--------------------------------------------------
\pagebreak
\thispagestyle{empty}
{\small
Copyright \copyright ~2012 Allen Downey.
\vspace{0.2in}
\begin{flushleft}
Green Tea Press \\
9 Washburn Ave \\
Needham MA 02492
\end{flushleft}
Permission is granted to copy, distribute, and/or modify this document
under the terms of the Creative Commons Attribution-NonCommercial 3.0 Unported
License, which is available at \url{http://creativecommons.org/licenses/by-nc/3.0/}.
The original form of this book is \LaTeX\ source code. Compiling this
\LaTeX\ source has the effect of generating a device-independent
representation of a textbook, which can be converted to other formats
and printed.
The \LaTeX\ source for this book is available from
\url{http://www.thinkpython.com}
\vspace{0.2in}
} % end small
\end{latexonly}
% HTMLONLY
\begin{htmlonly}
% TITLE PAGE FOR HTML VERSION
{\Large \thetitle}
{\large Allen B. Downey}
Version \theversion
\thedate
\setcounter{chapter}{-1}
\end{htmlonly}
\fi
% END OF THE PART WE SKIP FOR PLASTEX
\chapter{Preface 前言}
\section*{The strange history of this book 本书与众不同的历史}
In January 1999 I was preparing to teach an introductory programming
class in Java. I had taught it three times and I was getting
frustrated. The failure rate in the class was too high and, even for
students who succeeded, the overall level of achievement was too low.
1999年1月,我正准备使用Java教一门编程入门课程。
我之前已经教了三次,并且感到很沮丧。
课程的不及格率太高,即使对于及格的学生,整体的收获也太低。
One of the problems I saw was the books.
They were too big, with too much unnecessary detail about Java, and
not enough high-level guidance about how to program. And they all
suffered from the trap door effect: they would start out easy,
proceed gradually, and then somewhere around Chapter 5 the bottom would
fall out. The students would get too much new material, too fast,
and I would spend the rest of the semester picking up the pieces.
我看到的问题之一是教材。
它们都太大了,有太多不必要的关于Java的细节,
并且缺乏关于如何编程的上层的指导。
同时,它们也缺乏陷阱门效应(trap door effect),即从简单之处开始,并逐渐深入。
因此,大概到第五章左右,后面的学生开始掉队了。
学生们获得太多的材料,进展太快,并且我在剩下的学期选择一些片段。
Two weeks before the first day of classes, I decided to write my
own book.
My goals were:
在开始上课前两周,我决定写一本自己的书。
我的目标是:
\begin{itemize}
\item Keep it short. It is better for students to read 10 pages
than not read 50 pages.
尽量简短。对于学生,读10页比读50页好。
\item Be careful with vocabulary. I tried to minimize the jargon
and define each term at first use.
关注术语表。我试图使用最少的术语并且在第一次使用的时候给出定义。
\item Build gradually. To avoid trap doors, I took the most difficult
topics and split them into a series of small steps.
循序渐进。为了避免陷阱门,我将最难的主题拆分成一系列小的步骤。
\item Focus on programming, not the programming language. I included
the minimum useful subset of Java and left out the rest.
聚焦于编程,而不是编程语言。我只包括了Java最小的有用的子集,
并且忽略其余的。
\end{itemize}
I needed a title, so on a whim I chose {\em How to Think Like
a Computer Scientist}.
我需要一个标题,所以一时兴起,我选择了《如何像计算机科学家一样思考》。
My first version was rough, but it worked. Students did the reading,
and they understood enough that I could spend class time on the hard
topics, the interesting topics and (most important) letting the
students practice.
第一版很粗糙,但是它有效。学生们读它,并且他们足够理解它。
然后我可以将上课时间花在那些难的、有趣的主题上,
并且让学生们实践(这点最重要)。
I released the book under the GNU Free Documentation License,
which allows users to copy, modify, and distribute the book.
\index{GNU Free Documentation License}
\index{Free Documentation License, GNU}
我将此书以GNU自由文档许可的形式发布,
该许可允许用户拷贝、修改并且发布此书。
What happened next is the cool part. Jeff Elkner, a high school
teacher in Virginia, adopted my book and translated it into
Python. He sent me a copy of his translation, and I had the
unusual experience of learning Python by reading my own book.
As Green Tea Press, I published the first Python version in 2001.
\index{Elkner, Jeff}
接下来发生的非常棒。
弗吉尼亚一所高中的教师,Jeff Elkne修改了我的书并且翻译成了Python。
他将他的翻译发给了我一份,我有了一个与众不同的学习Python的体验,
即通过读我自己的书。
2001年,通过绿茶出版社(Green Tea Press),我发表了本书的第一个Python版本。
In 2003 I started teaching at Olin College and I got to teach
Python for the first time. The contrast with Java was striking.
Students struggled less, learned more, worked on more interesting
projects, and generally had a lot more fun.
\index{Olin College}
2003年,我开始在Olin College教书,并且第一次教Python。
与教Java的对比很显著,学生需要付出的努力更少,学到的更多,
他们致力于更有趣的项目,并且通常更快乐。
Over the last nine years I continued to develop the book,
correcting errors, improving some of the examples and
adding material, especially exercises.
过去9年我一直在改进这本书,纠正一些错误,改进一些实例,
增加一些材料,特别是练习题。
The result is this book, now with the less grandiose title
{\em Think Python}. Some of the changes are:
本书的结果是,现在有了一个更具体的名字《Think Python》。
下面是一些变化:
\begin{itemize}
\item I added a section about debugging at the end of each chapter.
These sections present general techniques for finding and avoiding
bugs, and warnings about Python pitfalls.
每章最后,我都增加了一节关于调试(debugging)的内容。
这些小节给出关于发现和避免一些错误的通常的技术,
以及关于Python的陷阱。
\item I added more exercises, ranging from short tests of
understanding to a few substantial projects. And I wrote
solutions for most of them.
增加了更多的练习题,涵盖了从为了理解的简短的测试到真正的项目。
并且为其中大部分写了答案。
\item I added a series of case studies---longer examples with
exercises, solutions, and discussion. Some are based on
Swampy, a suite of Python programs I wrote for use in my classes.
Swampy, code examples, and some solutions are available from
\url{http://thinkpython.com}.
我增加了一系列范例分析(case studies),
即具有联系、答案以及讨论的更长的样例。
其中一些基于Swampy,我写的一套用于我的课程的Pythong程序。
Swampy、代码样例、以及一些答案可以从 \url{http://thinkpython.com} 获得。
\item I expanded the discussion of program development plans
and basic design patterns.
我扩展了关于程序开发规划和基本设计模式的讨论。
\item I added appendices about debugging, analysis of algorithms, and
UML diagrams with Lumpy.
我增加了关于调试、算法分析以及使用Lumpy画UML图的附录。
\end{itemize}
I hope you enjoy working with this book, and that it helps
you learn to program and think, at least a little bit, like
a computer scientist.
我希望你能使用该书愉快的工作,并且它能帮助你学习编程和思考,
至少或多或少像一个计算机科学家。
Allen B. Downey \\
Needham MA\\
Allen Downey is a Professor of Computer Science at
the Franklin W. Olin College of Engineering.
Allen Downey是Franklin W. Olin工学院一名计算机科学教授。
\section*{Acknowledgments}
Many thanks to Jeff Elkner, who
translated my Java book into Python, which got this project
started and introduced me to what has turned out to be my
favorite language.
\index{Elkner, Jeff}
Thanks also to Chris Meyers, who contributed several sections
to {\em How to Think Like a Computer Scientist}.
\index{Meyers, Chris}
Thanks to the Free Software Foundation for developing
the GNU Free Documentation License, which helped make
my collaboration with Jeff and Chris possible, and Creative
Commons for the license I am using now.
\index{GNU Free Documentation License}
\index{Free Documentation License, GNU}
\index{Creative Commons}
Thanks to the editors at Lulu who worked on
{\em How to Think Like a Computer Scientist}.
Thanks to all the students who worked with earlier
versions of this book and all the contributors (listed
below) who sent in corrections and suggestions.
\section*{Contributor List}
\index{contributors}
More than 100 sharp-eyed and thoughtful readers have sent in
suggestions and corrections over the past few years. Their
contributions, and enthusiasm for this project, have been a
huge help.
If you have a suggestion or correction, please send email to
{\tt feedback@thinkpython.com}. If I make a change based on your
feedback, I will add you to the contributor list
(unless you ask to be omitted).
If you include at least part of the sentence the
error appears in, that makes it easy for me to search. Page and
section numbers are fine, too, but not quite as easy to work with.
Thanks!
\begin{itemize}
\small
\item Lloyd Hugh Allen sent in a correction to Section 8.4.
\item Yvon Boulianne sent in a correction of a semantic error in
Chapter 5.
\item Fred Bremmer submitted a correction in Section 2.1.
\item Jonah Cohen wrote the Perl scripts to convert the
LaTeX source for this book into beautiful HTML.
\item Michael Conlon sent in a grammar correction in Chapter 2
and an improvement in style in Chapter 1, and he initiated discussion
on the technical aspects of interpreters.
\item Benoit Girard sent in a
correction to a humorous mistake in Section 5.6.
\item Courtney Gleason and Katherine Smith wrote {\tt horsebet.py},
which was used as a case study in an earlier version of the book. Their
program can now be found on the website.
\item Lee Harr submitted more corrections than we have room to list
here, and indeed he should be listed as one of the principal editors
of the text.
\item James Kaylin is a student using the text. He has submitted
numerous corrections.
\item David Kershaw fixed the broken {\tt catTwice} function in Section
3.10.
\item Eddie Lam has sent in numerous corrections to Chapters
1, 2, and 3.
He also fixed the Makefile so that it creates an index the first time it is
run and helped us set up a versioning scheme.
\item Man-Yong Lee sent in a correction to the example code in
Section 2.4.
\item David Mayo pointed out that the word ``unconsciously"
in Chapter 1 needed
to be changed to ``subconsciously".
\item Chris McAloon sent in several corrections to Sections 3.9 and
3.10.
\item Matthew J. Moelter has been a long-time contributor who sent
in numerous corrections and suggestions to the book.
\item Simon Dicon Montford reported a missing function definition and
several typos in Chapter 3. He also found errors in the {\tt increment}
function in Chapter 13.
\item John Ouzts corrected the definition of ``return value"
in Chapter 3.
\item Kevin Parks sent in valuable comments and suggestions as to how
to improve the distribution of the book.
\item David Pool sent in a typo in the glossary of Chapter 1, as well
as kind words of encouragement.
\item Michael Schmitt sent in a correction to the chapter on files
and exceptions.
\item Robin Shaw pointed out an error in Section 13.1, where the
printTime function was used in an example without being defined.
\item Paul Sleigh found an error in Chapter 7 and a bug in Jonah Cohen's
Perl script that generates HTML from LaTeX.
\item Craig T. Snydal is testing the text in a course at Drew
University. He has contributed several valuable suggestions and corrections.
\item Ian Thomas and his students are using the text in a programming
course. They are the first ones to test the chapters in the latter half
of the book, and they have made numerous corrections and suggestions.
\item Keith Verheyden sent in a correction in Chapter 3.
\item Peter Winstanley let us know about a longstanding error in
our Latin in Chapter 3.
\item Chris Wrobel made corrections to the code in the chapter on
file I/O and exceptions.
\item Moshe Zadka has made invaluable contributions to this project.
In addition to writing the first draft of the chapter on Dictionaries, he
provided continual guidance in the early stages of the book.
\item Christoph Zwerschke sent several corrections and
pedagogic suggestions, and explained the difference between {\em gleich}
and {\em selbe}.
\item James Mayer sent us a whole slew of spelling and
typographical errors, including two in the contributor list.
\item Hayden McAfee caught a potentially confusing inconsistency
between two examples.
\item Angel Arnal is part of an international team of translators
working on the Spanish version of the text. He has also found several
errors in the English version.
\item Tauhidul Hoque and Lex Berezhny created the illustrations
in Chapter 1 and improved many of the other illustrations.
\item Dr. Michele Alzetta caught an error in Chapter 8 and sent
some interesting pedagogic comments and suggestions about Fibonacci
and Old Maid.
\item Andy Mitchell caught a typo in Chapter 1 and a broken example
in Chapter 2.
\item Kalin Harvey suggested a clarification in Chapter 7 and
caught some typos.
\item Christopher P. Smith caught several typos and helped us
update the book for Python 2.2.
\item David Hutchins caught a typo in the Foreword.
\item Gregor Lingl is teaching Python at a high school in Vienna,
Austria. He is working on a German translation of the book,
and he caught a couple of bad errors in Chapter 5.
\item Julie Peters caught a typo in the Preface.
\item Florin Oprina sent in an improvement in {\tt makeTime},
a correction in {\tt printTime}, and a nice typo.
\item D.~J.~Webre suggested a clarification in Chapter 3.
\item Ken found a fistful of errors in Chapters 8, 9 and 11.
\item Ivo Wever caught a typo in Chapter 5 and suggested a clarification
in Chapter 3.
\item Curtis Yanko suggested a clarification in Chapter 2.
\item Ben Logan sent in a number of typos and problems with translating
the book into HTML.
\item Jason Armstrong saw the missing word in Chapter 2.
\item Louis Cordier noticed a spot in Chapter 16 where the code
didn't match the text.
\item Brian Cain suggested several clarifications in Chapters 2 and 3.
\item Rob Black sent in a passel of corrections, including some
changes for Python 2.2.
\item Jean-Philippe Rey at Ecole Centrale
Paris sent a number of patches, including some updates for Python 2.2
and other thoughtful improvements.
\item Jason Mader at George Washington University made a number
of useful suggestions and corrections.
\item Jan Gundtofte-Bruun reminded us that ``a error'' is an error.
\item Abel David and Alexis Dinno reminded us that the plural of
``matrix'' is ``matrices'', not ``matrixes''. This error was in the
book for years, but two readers with the same initials reported it on
the same day. Weird.
\item Charles Thayer encouraged us to get rid of the semi-colons
we had put at the ends of some statements and to clean up our
use of ``argument'' and ``parameter''.
\item Roger Sperberg pointed out a twisted piece of logic in Chapter 3.
\item Sam Bull pointed out a confusing paragraph in Chapter 2.
\item Andrew Cheung pointed out two instances of ``use before def.''
\item C. Corey Capel spotted the missing word in the Third Theorem
of Debugging and a typo in Chapter 4.
\item Alessandra helped clear up some Turtle confusion.
\item Wim Champagne found a brain-o in a dictionary example.
\item Douglas Wright pointed out a problem with floor division in
{\tt arc}.
\item Jared Spindor found some jetsam at the end of a sentence.
\item Lin Peiheng sent a number of very helpful suggestions.
\item Ray Hagtvedt sent in two errors and a not-quite-error.
\item Torsten H\"{u}bsch pointed out an inconsistency in Swampy.
\item Inga Petuhhov corrected an example in Chapter 14.
\item Arne Babenhauserheide sent several helpful corrections.
\item Mark E. Casida is is good at spotting repeated words.
\item Scott Tyler filled in a that was missing. And then sent in
a heap of corrections.
\item Gordon Shephard sent in several corrections, all in separate
emails.
\item Andrew Turner {\tt spot}ted an error in Chapter 8.
\item Adam Hobart fixed a problem with floor division in {\tt arc}.
\item Daryl Hammond and Sarah Zimmerman pointed out that I served
up {\tt math.pi} too early. And Zim spotted a typo.
\item George Sass found a bug in a Debugging section.
\item Brian Bingham suggested Exercise~\ref{exrotatepairs}.
\item Leah Engelbert-Fenton pointed out that I used {\tt tuple}
as a variable name, contrary to my own advice. And then found
a bunch of typos and a ``use before def.''
\item Joe Funke spotted a typo.
\item Chao-chao Chen found an inconsistency in the Fibonacci example.
\item Jeff Paine knows the difference between space and spam.
\item Lubos Pintes sent in a typo.
\item Gregg Lind and Abigail Heithoff suggested Exercise~\ref{checksum}.
\item Max Hailperin has sent in a number of corrections and
suggestions. Max is one of the authors of the extraordinary {\em
Concrete Abstractions}, which you might want to read when you are
done with this book.
\item Chotipat Pornavalai found an error in an error message.
\item Stanislaw Antol sent a list of very helpful suggestions.
\item Eric Pashman sent a number of corrections for Chapters 4--11.
\item Miguel Azevedo found some typos.
\item Jianhua Liu sent in a long list of corrections.
\item Nick King found a missing word.
\item Martin Zuther sent a long list of suggestions.
\item Adam Zimmerman found an inconsistency in my instance
of an ``instance'' and several other errors.
\item Ratnakar Tiwari suggested a footnote explaining degenerate
triangles.
\item Anurag Goel suggested another solution for \verb"is_abecedarian"
and sent some additional corrections. And he knows how to
spell Jane Austen.
\item Kelli Kratzer spotted one of the typos.
\item Mark Griffiths pointed out a confusing example in Chapter 3.
\item Roydan Ongie found an error in my Newton's method.
\item Patryk Wolowiec helped me with a problem in the HTML version.
\item Mark Chonofsky told me about a new keyword in Python 3.
\item Russell Coleman helped me with my geometry.
\item Wei Huang spotted several typographical errors.
\item Karen Barber spotted the the oldest typo in the book.
\item Nam Nguyen found a typo and pointed out that I used the Decorator
pattern but didn't mention it by name.
\item St\'{e}phane Morin sent in several corrections and suggestions.
\item Paul Stoop corrected a typo in \verb+uses_only+.
\item Eric Bronner pointed out a confusion in the discussion of the
order of operations.
\item Alexandros Gezerlis set a new standard for the number and
quality of suggestions he submitted. We are deeply grateful!
\item Gray Thomas knows his right from his left.
\item Giovanni Escobar Sosa sent a long list of corrections and
suggestions.
\item Alix Etienne fixed one of the URLs.
\item Kuang He found a typo.
\item Daniel Neilson corrected an error about the order of operations.
\item Will McGinnis pointed out that {\tt polyline} was defined
differently in two places.
\item Swarup Sahoo spotted a missing semi-colon.
\item Frank Hecker pointed out an exercise that was under-specified, and
some broken links.
\item Animesh B helped me clean up a confusing example.
\item Martin Caspersen found two round-off errors.
\item Gregor Ulm sent several corrections and suggestions.
\item Dimitrios Tsirigkas suggested I clarify an exercise.
\item Carlos Tafur sent a page of corrections and suggestions.
\item Martin Nordsletten found a bug in an exercise solution.
\item Lars O.D. Christensen found a broken reference.
% ENDCONTRIB
\end{itemize}
\normalsize
\clearemptydoublepage
% TABLE OF CONTENTS
\begin{latexonly}
\tableofcontents
\clearemptydoublepage
\end{latexonly}
% START THE BOOK
\mainmatter
\chapter{The way of the program 编程的方法}
The goal of this book is to teach you to think like a
computer scientist. This way of thinking combines some of the best features
of mathematics, engineering, and natural science. Like mathematicians,
computer scientists use formal languages to denote ideas (specifically
computations). Like engineers, they design things, assembling components
into systems and evaluating tradeoffs among alternatives. Like scientists,
they observe the behavior of complex systems, form hypotheses, and test
predictions.
\index{problem solving}
本书的目标是教给你像计算机科学家一样思考。
这一思考的方式集成了数学、工程以及自然科学的一些最好的特点。
像数学家一样,计算机科学家使用形式语言表示思想(特别是计算)。
像工程师一样,计算机科学家设计东西,将零件组成系统,在各种选择之间寻求平衡。
像科学家一样,计算机科学家观察复杂系统的行为,形成假设并且对预测进行检验。
The single most important skill for a computer scientist is {\bf
problem solving}. Problem solving means the ability to formulate
problems, think creatively about solutions, and express a solution clearly
and accurately. As it turns out, the process of learning to program is an
excellent opportunity to practice problem-solving skills. That's why
this chapter is called, ``The way of the program.''
对于计算机科学家,唯一最重要的技能是{\bf 解决问题(problem solving)}。
解决问题意味着对问题进行形式化、对解决方案创新地思考以及清晰、精确地表达解决方案的能力。
事实证明,学习编程的过程是一个极佳的实践解决问题技能的机会。
这也是为什么本章被称为``编程的方法''。
On one level, you will be learning to program, a useful
skill by itself. On another level, you will use programming as a means to
an end. As we go along, that end will become clearer.
一个层面上,你将学习编程,本身就是一个有用的技能。
另一个层面上,你将使用编程作为达到目的的手段。
随着我们的深入,这将变得更清晰。
\section{The Python programming language Python编程语言}
\index{programming language}
\index{language!programming}
The programming language you will learn is Python. Python is
an example of a {\bf high-level language}; other high-level languages
you might have heard of are C, C++, Perl, and Java.
你将学习的编程语言是Python。Python是{\bf 高级语言(high-level language)}的一个例子;
其它你可能听说的高级语言包括C、C++、Perl以及Java。
There are
also {\bf low-level languages}, sometimes referred to as ``machine
languages'' or ``assembly languages.'' Loosely speaking, computers
can only run programs written in low-level languages. So
programs written in a high-level language have to be processed before
they can run. This extra processing takes some time, which is a small
disadvantage of high-level languages.
\index{portability}
\index{high-level language}
\index{low-level language}
\index{language!high-level}
\index{language!low-level}
另外也有{\bf 低级语言(low-level languages)},有时指``机器语言''或``汇编语言''。
大概来讲,计算机只能运行低级语言写的程序。
因此使用高级语言写的程序运行之前必须被处理。
这一额外的处理过程将花些时间,这是高级语言的一个小缺点。
The advantages are enormous. First, it is much easier to program
in a high-level language. Programs written in a high-level language
take less time to write, they are shorter and easier to read, and they
are more likely to be correct. Second, high-level languages are {\bf
portable}, meaning that they can run on different kinds of computers
with few or no modifications. Low-level programs can run on only one
kind of computer and have to be rewritten to run on another.
优点是巨大的。首先,使用高级语言编程要容易的多。
用高级语言写程序需要花更少的时间,它们更短、更易读并且更有可能正确。
其次,高级语言是{\bf 可移植的(portable)},也就是说只需很少的修改或者无需修改,
它们就可以运行在不同类型的计算机上。
低级语言只能运行于一种类型的计算机上,如果要运行于其它类型的计算机上,
不得不进行重写。
Due to these advantages, almost all programs are written in high-level
languages. Low-level languages are used only for a few specialized
applications.
\index{compile}
\index{interpret}
由于这些优点,几乎所有的程序都是用高级语言写的。
低级语言只被用于很少的特殊应用。
Two kinds of programs process high-level languages into low-level
languages: {\bf interpreters} and {\bf compilers}. An interpreter
reads a high-level program and executes it, meaning that it does what
the program says. It processes the program a little at a time,
alternately reading lines and performing computations.
Figure~\ref{fig.interpret} shows the structure of an interpreter.
\index{source code}
\index{object code}
\index{executable}
将高级语言处理成低级语言有两种程序:{\bf 解释器(interpreters)}和{\bf 编译器(compilers)}。
解释器读高级语言程序并且执行它,也就是说它按照程序说的去做。
它一次处理一些程序,交替地读几行程序并且执行计算。
图~\ref{fig.interpret} 展示了一个解释器的结构。
\begin{figure}
\centerline
{\includegraphics[scale=0.9]{figs/interpret.pdf}}
\caption{An interpreter processes the program a little at a time,
alternately reading lines and performing computations.
解释器一次处理一些程序,交替地读几行程序并且执行计算。}
\label{fig.interpret}
\end{figure}
A compiler reads the program and translates it completely before the
program starts running. In this context, the high-level program is
called the {\bf source code}, and the translated program is called the
{\bf object code} or the {\bf executable}. Once a program is
compiled, you can execute it repeatedly without further translation.
Figure~\ref{fig.compile} shows the structure of a compiler.
编译器在程序开始运行之前,读取整个程序并且将其全部翻译。
在这种情况下,高级语言程序被称为{\bf 源代码(source code)},
翻译后的程序被称为{\bf 目标代码(object code)}或者{\bf 可执行代码(executable)}。
一旦一个程序被编译,你可以重复的执行它无需再翻译。
图~\ref{fig.compile} 展示了一个编译器的结构。
\begin{figure}
\centerline
{\includegraphics[scale=0.9]{figs/compile.pdf}}
\caption{A compiler translates source code into object code, which is
run by a hardware executor.
编译器将源代码翻译成可被硬件执行的目标代码。}
\label{fig.compile}
\end{figure}
Python is considered an interpreted language because Python programs
are executed by an interpreter. There are two ways to use the
interpreter: {\bf interactive mode} and {\bf script mode}. In
interactive mode, you type Python programs and the interpreter displays
the result:
\index{interactive mode}
\index{script mode}
Python被认为是解释性语言,因为Python程序被解释器执行。
有两种方法使用解释器:{\bf 交互式模式(interactive mode)}和{\bf 脚本模式(script mode)}。
在交互式模式下,你键入Python程序,解释器显示结果:
\begin{verbatim}
>>> 1 + 1
2
\end{verbatim}
%
The chevron, \verb">>>", is the
{\bf prompt} the interpreter uses to indicate that it is ready. If
you type {\tt 1 + 1}, the interpreter replies {\tt 2}.
\index{prompt}
\verb">>>"是{\bf 提示符(prompt)},解释器用其表示它准备好了。
如果你键入{\tt 1 + 1},解释器回复{\tt 2}。
Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a {\bf script}. By
convention, Python scripts have names that end with {\tt .py}.
\index{script}
另外,你可以将代码存储在一个文件中,并且用解释器执行这个文件的内容,
其被称为{\bf 脚本(script)}。习惯上,Python脚本以{\tt .py}结尾命名。
To execute the script, you have to tell the interpreter the name of
the file. If you have a script named {\tt dinsdale.py} and you are
working in a UNIX command window, you type {\tt python
dinsdale.py}. In other development environments, the details of
executing scripts are different. You can find instructions for
your environment at the Python website \url{http://python.org}.
\index{testing!interactive mode}
为了执行脚本,你必须告诉解释器文件名。
如果你有一个命名为{\tt dinsdale.py}的脚本并且你在UNIX命令窗口中工作,
你键入{\tt python dinsdale.py}。在其它的开发环境中,
执行脚本的细节不太一样。
你可以在Python网站\url{http://python.org}中找到对于你的环境的说明。
Working in interactive mode is convenient for testing small pieces of
code because you can type and execute them immediately. But for
anything more than a few lines, you should save your code
as a script so you can modify and execute it in the future.
在交互模式中工作便于测试零散的代码,因为你可以立即键入并且执行它们。
但是对于任何多于几行的代码,你应该保存你的代码为脚本以便将来修改并执行它。
\section{What is a program? 什么是程序?}
A {\bf program} is a sequence of instructions that specifies how to
perform a computation. The computation might be something
mathematical, such as solving a system of equations or finding the