THE PRACTICE OF
COMPUTING USING
^l^S^^^^^^^^^^S^^^ ^.1^L^ gs|*^gs| (s^S^^^^S^^ ^S^^^^ls
M&T M M mlKlkMAm
sSSr 'SSf iffy
(*jW>>(ggu
^SBBfr<ggV
WILLIAM PUNCH
RICHARD ENBODY Michigan State University
Addis on-Wesley
Boston Columbus
Indianapolis
NewYork SanFranciscoUpper
Saddle River.Amsterdam Cape Town
Dubai London Madrid Milan Munich Paris Montreal Toronto Delhi MexicoCity
SaoPauloSydney
HongKong
Seoul Sinaanm-e Tainei TokvoCONTENTS
PREFACE xxi
PART 1 THINKING ABOUT COMPUTING 1
Chapter
0 TheStudy
ofComputer
Science 30.1
Why Computer
Science? 3Importance
ofComputer
Science 3Computer
"Science" 4Computer
ScienceThrough Computer Programming
50.2 The
Difficulty
and Promise ofProgramming
6Difficulty
1:TwoThings
atOnce 6Difficulty
2:What isaGoodProgram?
8ThePromiseofa
Computer Program
100.3
Choosing
aComputer Language
10Different
Computer Languages
10Why Python?
11Is
Python
theBestLanguage?
120.4 What is
Computation?
120.5
What
isaComputer?
13Computation
in Nature 13The Human
Computer
160.6 TheModern, Electronic
Computer
17It's the Switch! 17
The
Transistor 190.7 A
High-Level
Lookat aModernComputer
230.8
Representing
Data 25Binary
Data 25"Working
withBinary
26Limits 27
viii
CONTENTSRepresenting
Letters 28Representing
Other Data 29"WhatDoesaNumber
Represent?
30HowtoTalk About
Quantities
of Data 31 How MuchData isThat? 310.9 Overview of
Coming Chapters
32Summary
33PART 2 STARTING TO PROGRAM 35
Chapter
1Beginnings
371.1
Practice,
Practice, Practice 371.2
QuickStart,
theCircumferenceProgram
38Examining
the Code 401.3 AnInteractive Session 41 1.4 Parts ofa
Program
43Modules
43
Statements and
Expressions 43 Whitespace 45
Comments 46
Special Python
Elements: Tokens 46Naming Objects
481.5 Variables 49
Variable Creation and
Assignment
501.6
Objects
andTypes
52Numbers 55
Other Built-in
Types
57Object Types:
Not VariableTypes
58Constructing
New Values 591.7
Operators
61Integer Operators
61Floating
PointOperators
62Mixed
Operations
62Order of
Operations
and Parentheses 63Augmented Assignment Operators:
AShortcut! 641.8 Your First
Module,
Math 66 1.9Developing
anAlgorithm 67
1.10 Conclusion 70
CONTENTS
iX
1.11 Visual
Vignette:
TurtleGraphics
70Exercises 72
Programming Projects
76Chapter
2 Control 792.1 The Selection Statement for Decisions:
if
79Booleans forDecisions 80 The
if
Statement 81Example:
What Lead is SafeinBasketball? 84Repetition
88Example: Finding
Perfect Numbers 92Example: Classifying
Numbers 962.2
In-Depth
Control 99True and False: Booleans 99 Boolean Variables 100 Relational
Operators
100Boolean
Operators
105Precedence 106
Boolean
Operators Example
106Another Wordon
Assignments
110The SelectionStatementforDecisions 112 Moreon
Python
Decision Statements 113Repetition:
The whileStatement 116Sentinel
Loop
125Summary
ofRepetition
126Moreon
thenar
Statement 126Nesting
129Hailstone
Sequence Example
1292.3
Plotting
DatawithPylab
132FirstPlot and
Using
aList 132More
Interesting
Plot:aSine Wave134
2.4
Computer
SciencePerspectives:
Minimal UniversalComputing
136Summary
138Exercises 138
Programming Projects
144Chapter
3Algorithms
andProgram Development
1473.1 What isan
Algorithm?
147Example Algorithms
148X CONTENTS
3.2
Algorithm
Features 149Algorithm
VersusProgram
149Detailed 150 Effective 150
Specify
Behavior 151General-Purpose Algorithms
151Can We
Realty
Do All That? 152 3.3 WhatisaProgram?
152Readability
152Robust 155 Correctness 156
3.4
Strategies
forProgram Design
157Engage
and Commit 157Understand,
ThenVisualize 158Think Before You
Program
159Experiment
159Simplify
160Stop
andThink 161Relax: Give YourselfaBreak 161
3.5
ASimple Example
161Build the Skeleton 162
Output
162Input
163Doing
the Calculation 166Summary
171Exercises 171
PART 3 ORGANIZING: DATA STRUCTURES AND FUNCTIONS 173
Chapter
4Working with Strings
1754.1 The
String Type
175The
Triple Quote String
176Non
Printing
Characters 177String Representation
177Strings
as aSequence
178More
Indexing
andSlicing
1794.2
String Operations
183Concatenation
(+)
andRepetition (*)
184Determining
When +Indicates AdditionorConcatenation? 185
Comparison Operators
186CONTENTS
Xi
The in
Operator
187String
CollectionsareImmutable 188 4.3 APreview of Functions and Methods 189FirstCut: "What isaFunction? 189 A
String
Method 191Determining
MethodNames and MethodArguments
193String
Methods 195String
Functions196
4.4 Formatted
Output
forStrings 196 Descriptor
Codes 197Width Descriptor
198Floating-Point
PrecisionDescriptor
1994.5 Control and
Strings
2004.6
Working
withStrings
203Example: Reordering
aPersons Name 203 Palindromes 2054.7 Example: Counting
PokerHands
208Program
toCount Poker Hands 211Summary
218Exercises 218
Programming Projects
222Chapter
5Functions—QuickStart
2275.1 WhatisaFunction? 227
Why
HaveFunctions? 2285.2
Python
Functions 2295.3 Flow of Control with Functions 231 Function Flow in Detail 232 AnotherFunction
Example
235Function
Example:
Word Puzzle 236 FunctionsCalling
Functions 242WhentoUseaFunction 242
What if Thereis No Return Statement? 243 WhatifThere Are
Multiple
ReturnStatements?
243
5.4 Visual
Vignette:
TurtleFlag
244Summary
245Exercises
245
Programming Projects
249Xii
CONTENTSChapter
6 ListsandTuples
2516.1 WhatisaList? 251
6.2 WhatYou
Already
Know HowtoDo with Lists 253Indexing
andSlicing
253Operators
254Functions
256
ListIteration 256 6.3 New
Things
inLists 256ListsareMutable 256 List Methods 258
6.4 Old and New Friends:
Range, Split,
and Other Functions and Methods 261Range, Split,
andMultiple Assignment
261Listto
String
and BackAgain, Using j
oin 262The Sorted Function 263
6.5
Working
with SomeExamples
264Anagrams
264Example:
FileAnalysis
2686.6 Mutable
Objects
and References 273 Shallowvs.Deep Copy
277MutableversusImmutable 280
6.7 Tuples
281Tuples
from Lists 282Why Tuples?
2836.8 Lists: The Data Structure 283
Example
Data Structure 284 OtherExample
Data Structures 2856.9
Algorithm Example
U.S. EPA AutomobileMileage
Data 286
6.10
Python
Diversion: ListComprehension
2966.11 Visual
Vignette:
MorePlotting
297Numpy Arrays
297Plotting Trigonometric
Functions 299Summary
300Exercises 300
Programming Projects
307Chapter
7 MoreonFunctions 3137.1 Functions
Calling
Functions 313CONTENTS
Xlii
7.2
Scope:
AFirst Cut 316Arguments,
Parameters, andNamespaces
317Passing
MutableObjects
319Returning
aComplex Object
321Refactoring
evens 3237-3 Default Values and Parametersas
Keywords 324 Example:
DefaultValues andParameterKeywords
325Issues with Default Values 326
7-4
FunctionsasObjects
328Docstrings
3287-5 Example: Determining
aFinalGrade 329TheData 329 The
Design
329Function:
weightedGrade
330 Function: grade 330Function: main 331
Example
Use 3327.6 Esoterica:
"by
value"or"by
reference" 332Summary
333Exercises 333
Programming Projects
336Chapter
8 Dictionaries and Sets 3418.1 Dictionaries
341 Dictionary Example
342Python
Dictionaries343
Dictionary Indexing
andAssignment
343Operators
3448.2 Word Count
Example
348Count Wordsina
String
348Word
Frequency
forGettysburg
Address349 Output
andComments 3538.3 Periodic Table
Example
354Working
with CSV Files354
Algorithm
Overview 356Functions for Divide and
Conquer 356
8.4 Sets 361
History
361What's inaSet? 361
Python
Sets361
XiV
CONTENTSMethods, Operators,
andFunctions forPython
Sets 362Set Methods 363 8.5 Set
Applications 367
Relationship
BetweenWords of Different Documents 367Output
andComments 3718.6
Scope:
The FullStory
371Namespaces
andScope
372Search
Rule forScope
372Local 372
Global
373 Built-Ins 377Enclosed
3788.7
Python
Pointer:Using
zip
toCreateDictionaries 379 8.8 VisualVignette:
BarGraph
ofWordFrequency
380Getting
theDataRight
381Labelsandthe xticks Command 381
Plotting
382Summary
383Exercises 383
Programming Projects
388Chapter
9 Files 3919.1
What
isaFile? 3919.2
Accessing
Files:Reading
Text Files 391Other File Access Methods 392
What's Really Happening? 394
9.3
Accessing
Files:Writing
Text Files394
9.4
Reading
andWriting
TextFilesinaProgram
3959.5 File Creationand
Overwriting 396
Universal New Line Format 397
Moving
AroundinaFile 3989.6
Closing
aFile 4009.7 CSVFiles 400 CSV Module 401 CSVReader 402 CSV Writer 403
Example: Update
Some Grades 4039.8
Example: Reprompting
fora"Good"
File Name 405CONTENTS XV
9.9 Module:os
407
Directory/Folder
Structure 408os
Module
Functions 409osModule
Example
411Summary
413Exercises 414
Programming Projects
415Chapter
10 MoreProgram Development 417
10.1 Introduction
417
10.2 Divide and
Conquer
417Top-Down
Refinement 41810.3 The Breast Cancer Classifier 418 The Problem 418
The
Approach:
Classification 419Training
andTesting
the Classifier 419Building
the Classifier 41910.4
Designing
the ClassifierAlgorithm
420Divided,
nowConquer
424Data Structures 425 File Format
425
Function:
makeTrainingSet
425The makeTestSet Function 430 The trainClassifier Function
431 trainClassifer,
Round2 433Testing
theClassifier
onNew Data 436The
reportResults
Function 44110.5
Running
the ClassifieronFull Data 442Training
versusTesting
44210.6 Other
Interesting
Problems 446Tag
Clouds 446S&P500Predictions 448
Predicting Religion
withFlags
450Summary 452
Exercises 452
Programming Projects 453
PART 4 CLASSES: MAKING YOUR OWN DATA STRUCTURES &
ALGORITHMS 455
Chapter
11 IntroductiontoClasses 457Simple
Student Class 45711.1
Object-Oriented Programming
458Python
isObject-Oriented!
458CharacteristicsofOOP 459
11.2
Working
withObject-Oriented Programming
459 Class andInstance 45911.3
Working
with Classes and Instances 460 Built-in Class andInstance 460OurFirstClass 461
Changing
Attributes 463The
Special Relationship
BetweenanInstance andClass:instance-of 465 11.4
Object
Methods467
Using Object
Methods 467Writing
Methods 469The
Special Argument
self 470Methodsare the
Interface
to a Class Instance472
11.5Fitting
into thePython
Class Model472
Making Programmer-Defined
Classes 472AStudent Class
473
Python
Standard Methods 473Now There Are Three: Class
Designer, Programmer,
and User 47811.6
Example:
Point Class 478 Construction 480 Distance 480Summing
Two Points 480Improving
thePointClass 48111.7
Python
and OOP 483Encapsulation 483
Inheritance 484
Polymorphism
48411.8 AnAside:
Python
and OtherOOPLanguages
484PublicversusPrivate 484
Indicating Privacy Using
Double Underscores(__) 485 Python's Philosophy
486Modifying
anInstance 48611.9 Conclusion
487
Exercises 487Programming Projects
488C 0 N T E
Chapter
12 MoreonClasses
49312.1 More About Class
Properties 493
Rational Number
(Fraction)
ClassExample
49412.2 How Does
Python
Know? 495Classes, Types,
andIntrospection 495
Remember
Operator Overloading
49712.3
Creating
Your OwnOperator Overloading
497Mapping Operators
toSpecial
Methods 49912.4
Building
the Rational Number Class 501Making
the Class 501Review Fraction Addition 503 Backto
Adding
Fractions 506Equality
andReducing
Fractions 510Divide and
Conquer
atWork 51312.5 What Doesn't Work
(Yet)
513Introspection
514Repairing
int+RationalErrors 51612.6 Inheritance 518
The "FindtheAttribute" Game 518
Using
Inheritance 521Example:
TheStandard Model 522Summary
528Exercises 528
Chapter
13Program Development
with Classes 533 13.1Predator-Prey
Problem 533TheRules 534
Simulation
Using Object-Oriented Programming
53513.2 Classes 535 IslandClass 535
Predator and
Prey,
Kinds of Animals 537 Predator andPrey
Classes541
Object Diagram
541Filling
the Island 54113.3
Adding
Behavior 544Refinement: AddMovement 544 Refinement:Time Simulation
Loop
54713.4 Refinement:
Eating, Breeding,
andKeeping
Time 548Improved
TimeLoop 549
Breeding
552xviii
CONTENTSEating
554The TickoftheClock 555 13.5 Refinements 556
Refinement:How
Many
TimestoMove? 556Refinement:
Graphing Population
Size 55713.6 Conclusion 559 Exercises 559
PART 5 BECOMING A
BETTER
PROGRAMMER 561Chapter
14Exceptions
andException Handling
56314.1
Introduction
56314.2 Basic
Exception Handling
565A
Simple Example 566
14.3 A
Philosophy Concerning Exceptions
56914.4
Exception:
elseandfinally
570Example: Refactoring
theReprompting
ofaFile Name 57014.5
Exception Usage
572Check
Input
572Check File
Opening
57314.6 Moreon
Exceptions 574
Raise 574
Create Your Own 575
14.7
Example:
PasswordManager 576 Summary
580Exercises 580
Chapter
15Testing
58315.1
Why Testing?
583Kinds of Errors 583
"Bugs"
andDebugging
58415.2 Kinds of
Testing
585Testing
is Hard! 586Importance
ofTesting
58715.3
Example
Problem 587NBA
Efficiency
588Basic
Algorithm
58815.4 Incorporating Testing
591Catching
User Errors 591Catching Developer
Errors 593CONTENTS
XiX
15.5 Automation of
Testing
595doctest 595
Other Kinds of
Testing 598
15.6 Conclusion 598 Exercises 599
Chapter
16 Recursion:AnotherControl Mechanism
601 16.1 Whatis Recursion? 60116.2 Mathematics andRabbits 603
16.3
Let's"Write Our Own:Reversing
aString
60616.4 How Does Recursion
Actually
Work? 608Stack Data Structure 609 Stacks andFunction Calls 611 16.5 Recursion in
Figures
613Recursive Tree 613
Sierpinski Triangles 615
16.6 RecursiontoNonrecursion 616 16.7 Conclusion 617
Exercises 617
APPENDICES 619
Appendix
AGetting
andUsing Python
619Appendix
BSimple Drawing
with TurtleGraphics
631Appendix
CPlotting
and Numeric Tools: AQuick Survey 635 Appendix
DPython
3.0 649Appendix
E Table of ASCII Values653 Appendix
F Precedence 655INDEX 657