The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by perpussmekar3, 2022-11-12 18:20:07

1. python programming

1. python programming

392 Chapter 13. Algorithm Design and Recursion

generates all anagrams of the word and then checks which (if any) are in the dictionary. The
anagrams appearing in the dictionary are printed as solutions to the puzzle.

Index message encoding, 109
quadratic equation three-way decision, 174
__doc__, 264 racquetball simulation
__init__, 256
__name__, 170 simOneGame, 231
selection sort, 371
abstraction, 228 simNGames, 229
accessor, 72 temperature conversion, 23
accumulator, 52 alias, 74
acronym, 133 anagrams
addinterest1.py, 151 recursive function, 367
addinterest2.py, 153 Analysis
addinterest3.py, 153 software development, 21
algorithm analysis of algorithms, 3, 360
and, 204
analysis, 3, 360 operational definition, 212
definition of, 3 Ants Go Marching, The, 161
design strategy, 186 append, 288
divide and conquer, 362 archery, 96, 190
exponential time, 381 argument, 9, 145
intractable, 381 array, 286
linear time, 361 associative, 308
log time, 361 arrow (on Lines), 90
quadratic (n-squared) time, 376 ASCII, 108
algorithms assignment statement, 14
average n numbers assignment statement, 28–30
semantics, 28
counted loop, 194 simultaneous, 32
empty string sentinel, 200 syntax, 28
interactive loop, 197 associative array, 308
binary search, 360 ATM simulation, 355
cannonball simulation, 249 attendee list, 355
future value, 37 attributes, 247
future value graph, 75, 79 private, 274
input validation, 208 average n numbers
linear search, 359 algorithm
max-of-three
comparing each to all, 181 empty string sentinel, 200
decision tree, 182 problem description, 193
sequential, 183 program
median, 291
merge sort, 373 counted loop, 194
message decoding, 110, 111
393

394 Index

empty string sentinel, 200 cannonball
end-of-file loop, 202 algorithm, 249
from file with readlines, 201 graphical display, 281
interactive loop, 197 problem description, 248
negative sentinel, 199 program, 251, 258, 266
average two numbers, 33 Projectile class, 257
average1.py, 194
average2.py, 197 card, 279, 319
average3.py, 199 deck of, 319
average4.py, 200
average5.py, 201 cball1.py, 251
average6.py, 202 cball3.py, 258
avg2.py, 33 cball4.py, 266
CButton, 279
babysitting, 190 CD, 4
base conversion, 388 Celsius, 22
batch processing, 128 censor, 319
change counter
example program, 128
binary, 6 program, 45, 123
binary search, 359 change.py, 45
bit, 55 change2.py, 123
black box, 323 chaos
Blackjack, 243
BMI (Body Mass Index), 189 discussion, 14–15
Boolean program, 10
chaos.py, 10
algebra (logic), 207 chr, 108
expression, 169, 204 Christmas, 96
operator, 204 cipher, 116
values, 169 ciphertext, 116
break statement, 209 Circle
implementing post-test loop, 209 constructor, 90
style considerations, 211 methods, 90
bridge (card game), 355 circle
Brooks, Fred, 325 area formula, 62
bug, 22 intersection with line, 96
butterfly effect, 15 class, 71, 248
Button class standing, 189
class definition, 269 class statement, 255
description, 268 classes
methods, 268, 269 Button, 269
button.py, 269 Calculator, 305
byte code, 11 Dice, 337
DieView, 271, 299
C-Curve, 390 GraphicsInterface, 346
Caesar cipher, 134 MSDie, 254
calculator Player, 331
PokerApp, 339
problem description, 301 Projectile, 257
program, 305 Projectile as module file, 264
RBallGame, 328

Index 395

SimStats, 327 decision, 165
Student, 259 definition of, 36
TextInterface, 341 loop, 36
client, 323 nested loops, 202
clone, 74, 89 nesting, 175
close control structures
GraphWin, 89 Boolean operators, 212
code duplication for statement, 36
in future value graph, 142 if, 167
maintenance issues, 138 if-elif-else, 176
reducing with functions, 138 if-else, 173
coffee, 62 while, 195
Collatz sequence, 217 convert.py, 23, 166
color convert2.py, 167
changing graphics object, 80 convert_gui.pyw, 86
changing GraphWin, 80 coordinates
fill, 80 as instance variables, 71
outline, 80 changing with setCoords, 81
specifying, 92 in a GraphWin, 69
color_rgb, 92 of a Point, 69
combinations, 388 setCoords example, 81
command shell, 8 transforming, 81
comments, 12 counted loop
compiler, 6 definition of, 34
diagram, 6 in Python, 35
vs. interpreter, 6 CPU (Central Processing Unit), 4
compound condition, 181 craps, 243
computer createLabeledWindow, 157
definition of, 1 cryptography, 116
functional view, 4 cube, 279
program, 2
computer science data, 45, 247
definition of, 3 data type
methods of investigation, 3
concatenation, 27 automatic conversion, 57
list, 286 definition of, 46
string, 101 explicit conversion, 57
condition, 168 mixed-type expressions, 57
compound, 181 string conversion, 119
design issues, 181 string conversions, 112
for termination, 208 data types
syntax, 168 file, 125
conditional loop, 195 float, 46
constructor, 71, 248 int, 46
__init__, 256 long int, 56
parameters in, 71 string, 99
control codes, 108 date, 190
control structure, 165 date conversion
program, 119, 120

396 Index

dateconvert.py, 119 problem description, 335
dateconvert2.py, 120 dice roller
day number, 190
debugging, 22 problem description, 267
decision, 165 program, 274
dictionary, 307
implementation via Boolean operator, 212 creation, 309
multi-way, 174 empty, 309
nested, 175 methods, 309
simple (one-way), 168 DieView, 296
two-way, 173 class definition, 271, 299
decision tree, 182 description, 271
deck, 319 Dijkstra, Edsger, 3
decoding, 110 disk, 4
algorithm, 110, 111 distance function, 148
program, 112 division, 48
definite loop, 195 docstring, 264
definition of, 34 dot notation, 11, 71
use as counted loop, 35 draw, 89
degree-days, 218 drawBar, 143
delete, 288 duplicate removal, 318
DeMorgan’s laws, 207 duplication, see code duplication
design, 22, 323 DVD, 4
object-oriented, see object-oriented design
top-down, 225 Easter, 190
elif, 176
steps in, 235 empty list, 288
design pattern empty string, 200
encapsulation, 263, 350
importance of, 195 encoding, 107
design patterns
algorithm, 109
counted loop, 34, 194 program, 109
end-of-file loop, 202 encryption, 116
interactive loop, 197 Entry, 86, 91–92
IPO, 23 environment, programming, 10
loop accumulator, 52, 194 epact, 63
model-view, 336 equality, 169
nested loops, 202, 204 Eratosthenes, 318
sentinel loop, 198 error checking, 177
errors
loop and a half, 210 KeyError, 310
design techniques math domain, 51
name, 26
divide and conquer, 362 Euclid’s algorithm, 218
spiral development, 238 eval, 112
event, 84
when to use, 240 event loop, 275
dice, 244 event-driven, 84
dice poker exam grader, 133, 189

classes
Dice, 336, 337
GraphicsInterface, 346
PokerApp, 339
TextInterface, 341

Index 397

exception handling, 177 semantics, 34
exponential notation, 56 syntax, 34
expression using simultaneous assignment, 303
formal parameter, 145
as input, 31 format specifier, 122
Boolean, 169, 204 from..import, 68
definition of, 25 function, 8
spaces in, 26 actual parameters, 145
arguments, 9, 145
face, 96, 280 as black box, 323
fact.py, 364 as subprogram, 139
factorial call, 8, 145
createLabeledWindow, 157
definition of, 51 defining, 8, 144
program, 53 for modularity, 156
recursive definition, 363 invoking, see function, call
factorial.py, 53 missing return, 150
Fahrenheit, 22 multiple parameters, 147
fetch-execute cycle, 5 None as default return, 150
fib parameters, 9
recursive function, 370 recursive, 364
Fibonacci numbers, 64, 217, 370, 387 return value, 148
file, 125 returning multiple values, 150
closing, 126 signature (interface), 227
opening, 126 to reduce duplication, 138
processing, 126 function definition, 139
program to print, 127 functions
read operations, 126 anagrams, 367
representation, 125 built-in
write operations, 128
flash memory, 4 chr, 108
float, 46 eval, 112
literal, 46 float, 57
representation, 56 int, 57
floppy, 4 len, 102
flowchart, 36 max, 185
flowcharts open, 126
for loop, 36 ord, 108
if semantics, 168 range, 53
loop and a half sentinel, 211 read, 126
max-of-three decision tree, 183 readline, 126
max-of-three sequential solution, 184 readlines, 126
nested decisions, 175 round, 57
post-test loop, 209 str, 119
temperature conversion with warnings, 166 type, 46
two-way decision, 173 write, 128
while loop, 196 distance, 148
for statement (for loop), 34, 193 drawBar, 143
as counted loop, 35 fib, 370
flowchart, 36

398 Index

gameOver, 233 getInputs, 228
getInputs, 228 getMouse, 84, 89
getNumbers, 289
happy, 140 example use, 84
loopfib, 370 getNumbers, 289
loopPower, 367 getP1, 90
main, 10 getP2, 90
getPoints, 91
why use, 12 getRadius, 90
makeStudent, 262 getText, 91
math library, see math library, functions getX, 90
mean, 289 getY, 90
median, 291 gozinta, 48
merge, 373 GPA, 259
mergeSort, 375 gpa, 278
moveTower, 380
random library, see random library, functions program, 261
recPower, 368 GPA sort, 317
recursive binary search, 368
recursive factorial, 364 program, 295
reverse, 365, 366 gpa.py, 261
selsort, 372 gpasort, 317
simNGames, 230 gpasort.py, 295
simOneGame, 233 graphics library
singFred, 140
singLucy, 140 methods
square, 148 setCoords, 81
stdDev, 290
string library, see string library Graphics Group, 320
future value graphics library, 67, 88–92
algorithm, 37
problem description, 37 drawing example, 69
program, 38, 157 generic methods summary, 89
program specification, 37 graphical objects, 89–91
future value graph methods
final algorithm, 79
problem, 75 for Text, 91
program, 79, 82, 137, 143 clone, 74
rough algorithm, 75 for Circle, 90
futval.py, 38 for Entry, 91
futval_graph.py, 79 for Image, 92
futval_graph2.py, 82, 137 for Line, 90
futval_graph3.py, 143 for Oval, 90
futval_graph4.py, 157 for Point, 90
for Polygon, 91
gameOver, 233 for Rectangle, 90
GCD (Greatest Common Divisor), 218 getMouse, 84
getAnchor, 91, 92 move, 72
getCenter, 90 objects
Circle, 90
Entry, 86, 91–92
GraphWin, 67, 89
Image, 92
Line, 90
Oval, 90

Index 399

Point, 69, 90 from the right, 101
Polygon, 85, 91 list, 286, 289
Rectangle, 90 negative indexes, 101
Text, 91 string, 100
GraphWin, 67, 89 infinite loop, 196, 210
methods summary, 89 inheritance, 351
Gregorian epact, 63 inner product, 318
GUI, 66 innerProd, 318
input, 13
hailstone function, 217 validation, 208
halting problem, 382 input statement, 30
happy, 140 multiple values, 33
happy birthday semantics, 30
syntax, 30
lyrics, 139 Input/Output Devices, 4
problem description, 139 instance, 71, 248
program, 142 instance variable
happy.py, 142 accessing, 256
hard drive, 4 instance variable, 71, 247
hardware, 2 and object state, 256
hash array, 308 int, 46
hierarchy chart, see structure chart automatic conversion to float, 57
house, 97 literal, 46
house (of representatives), 190 range of, 55
representation, 55
identifier integer division, 48
definition of, 24 interest calculation
rules for forming, 24 program, 151, 153
interface, 227
IDLE, 10 interpreter, 6
if statement diagram, 7
Python, 7
flowchart, 168 vs. compiler, 6
semantics, 168 intractable problems, 3, 381
syntax, 167 investment doubling, 217
if-elif-else statement IPO (Input, Process, Output), 23
semantics, 176 iteration, 34
syntax, 176
if-else statement key
decision tree, 182 cipher, 117
nested, 175, 182 private, 117
semantics, 173 public, 117
syntax, 173 shared, 117
Image, 92 with dictionary, 308
implementation, 22
import statement key-value pair, 308
with “from”, 68 KeyError, 310
import statement, 50, 170 keywords, 24
indefinite loop, 195 Koch Curve, 389
indexing
dictionary, 309

400 Index

label, 77 interactive, 197
ladder, 63 loop and a half, 210
leap year, 190 nested, 202
len over a sequence, 34
post-test, 209
with string, 102
with list, 286, 290 using break, 209
lexicographic ordering, 169 using while, 209
library pre-test, 195
definition of, 49 while statement, 195
graphics, see graphics library loop and a half, 210
math, see math library loopfib, 370
random, see random library loopPower, 367
lightning, 62 lower, 129
Line, 90 Lucas, Édouard, 378
line continuation
using backslash (\), 124 machine code, 6
using brackets, 297 machine language, 6
linear time, 361 maintenance, 22
list, 35 makeStudent, 262
as sequence, 286 mapping, 308
creation, 288 math domain error, 51
empty, 288 math library, 49
indexing, 286
merging, 373 functions, 50, 51
methods, 288 using, 50
operators, 286 max, 185
removing items, 288 max-of-n program, 184
slice, 289 max-of-three, 180–183
vs. string, 286 maxn.py, 184
lists mean, 289
decorated, 318 median, 284, 291
literal, 25 memory, 4
float, 46 main, 4
int, 46 secondary, 4
string, 100, 265 merge, 373
log time, 361 merge sort, 373
long int, 56 mergeSort, 375
loop, 13 analysis, 376
accumulator variable, 52 message encoding
as control structure, 36 algorithm, 109
counted, 34, 35 message decoding
definite, 34, 195 algorithm, 110, 111
end-of-file, 202 problem description, 110
event loop, 275 program, 112
for statement, 34 message encoding
indefinite (conditional), 195 problem description, 107
index variable, 34 program, 109
infinite, 196, 210 meta-language, 27
method, 71, 247

Index 401

parameterless, 72 state, 72
accessor, 72 object-oriented, 65
call (invoke), 71, 255 object-oriented design (OOD), 323, 324
mutator, 72 objects
normal parameter, 256
object parameters, 72 built-in
self parameter, 255 None, 150
string, 111
methods graphics, see graphics library, objects
activate, 268 other, see classes
clicked, 269 objrball.py, 331
deactivate, 268 Old MacDonald, 161
dictionary, 309 one-way decision, 168
list, 288 open, 126
model-view, 336 operator
module file, 10 Boolean, 204
module hierarchy chart, see structure chart
molecular weight, 62 as control structure, 212
Monte Carlo, 223, 244 definition of, 26
month abbreviation precedence, 26, 205
problem description, 103 relational, 168
program, 104, 106 short-circuit, 213
month.py, 104 operators
month2.py, 106 Boolean, 204
move, 72, 89 del, 288
moveTower, 380 list, 286
MPG, 218 mathematical, 26
MSDie, 253 Python numeric operators, 47
mutable, 106, 308 relational, 168
mutator, 72 or, 204
operational definition, 212
NameError, 26 ord, 108
names, 24 output labeling, 28
nesting, 175 output statements, 27
newline character (\n), 125 Oval, 90
override, 352
with readline, 202 overtime, 189
Newton’s method, 64
None, 150 palindrome, 388
numbers2text.py, 112 parameter, 9
numerology, 133
actual, 145
object, 247 as function input, 147
aliasing, 74 formal, 145
application as, 301 matching by order, 147
as black box, 323 multiple, 147
as parameter, 72 objects as, 72
attributes, 247 removing code duplication, 141
definition of, 66 scope issues, 144, 145
self, 255
pi
math library, 51

402 Index

Monte Carlo approximation, 244 future value, 38
series approximation, 64 future value graph, 79, 82, 137, 143, 157
pixel, 68 gpa, 261
pizza, 62 GPA Sort, 295
plaintext, 116 happy birthday, 142
Player, 331 interest calculation, 151, 153
plot, 89 max-of-n, 184
plotPixel, 89 message decoding, 112
Point, 69, 90 message encoding, 109
poker, see dice poker month abbreviation, 104, 106
cards, 319 print file, 127
Polygon, 85, 91 quadratic equation, 49, 171, 173, 176, 177, 179
polymorphism, 351 racquetball simulation, 233
portability, 7 racquetball simulation (object version, 331
post-test loop, 209 simple statistics, 292
prime number, 217, 318 temperature conversion, 23, 86, 166, 167
priming read, 199 triangle, 85, 148
print statement, 8 turing: an impossible program, 383
semantics, 27 username generation, 103, 128
print statement, 27 word frequency, 313
syntax, 27 prompt
printfile.py, 127 Python, 8
private attributes, 274 using Text object, 86
private key encryption, 117 prototype, 238
program, 2 pseudo random numbers, 223
programming pseudocode, 23
definition of, 2 public key encryption, 117
environment, 10 pyc file, 11
event-driven, 84 Python
why learn, 2 Boolean operators, 204
programming language mathematical operators, 26
translation, 6 numeric operators, 47
programming language, 5–7 programming environment, 10
and portability, 7 relational operators, 168
vs. natural language, 5 reserved words, 25
examples, 5 running programs, 10
high-level, 5 pyw, 85
syntax, 27
programs quadratic equation, 49
average n numbers, 194, 197, 199–202 algorithm with three-way decision, 174
average two numbers, 33 decision flowchart, 173
calculator, 305 program, 49, 171
cannonball simulation, 251, 258, 266 program (bullet-proof), 179
change counter, 45, 123 program (simple if), 171
chaos, 10 program (two-way decision), 173
date conversion, 119, 120 program (using exception), 177
dice roller, 274 program (using if-elif-else), 176
factorial, 53
quadratic time, 376

Index 403

quadratic.py, 49, 171 regression line, 218, 281
quadratic2.py, 171 relational operator, 168
quadratic3.py, 173 repetition
quadratic4.py, 176
quadratic5.py, 177 list, 286
quadratic6.py, 179 string, 102
quiz grader, 133, 189 reserved words, 24
in Python, 25
racquetball, 206, 222 resolution, 76
racquetball simulation return statement, 148
multiple values, 150
classes reverse
RBallGame, 328 recursive function, 365, 366
roller.py, 274
racquetball simulation root beer, 51
algorithms round, 57
simNGames, 229
simOneGmae, 231 scientific notation, 56
classes scope, 144
Player, 331 screen resolution, 76
SimStats, 327 script, 10
discussion, 237 search, 357
problem description, 222 searching
program, 233
program (object version), 331 binary search, 359
specification, 222 linear search, 359
structure charts problem description, 358
level 2, 230 recursive formulation, 368
level 3, 232 seed, 223
top-level, 228 selection sort, see sorting, selection sort
self, 255
RAM (random access memory), 4 selSort, 372
random, 224 semantics, 5
random library, 224 senate, 190
sentinel, 198
functions sentinel loop, 198
random, 224 sequence operators, 286
randrange, 224 setArrow, 90
setBackground, 89
random numbers, 223 setCoords, 81, 89
random walk, 244, 320 example, 81
randrange, 224 setFace, 91
range, 35 setFill, 89
setOutline, 89
general form, 53 sets, 320
RBallGame, 328 setSize, 91
read, 126 setStyle, 91
readline, 126 setText, 91
readlines, 126 setWidth, 89
recBinSearch, 368 shell, 8
recPower

recursive function, 368
Rectangle, 90
recursion, 363

404 Index

shuffle, 318 spellchecker, 391
Sieve of Eratosthenes, 318 sphere, 62, 279
signature, 227
simNGames, 230 surface area formula, 62
simOneGame, 233 volume formula, 62
simple decision, 168 split, 111
simple statistics, 317 sqrt, 50
square function, 148
problem, 284 square root, 64
program, 292 stable sort, 313
SimStats, 327 standard deviation, 284
simulation, 221 statement, 8
simultaneous assignment, 32 statements
in for loop, 303 assignment, 14, 28–30
with multiple return values, 150 break, 209
singFred, 140 class, 255
singLucy, 140 comment, 12
slicing def (function definition), 8, 139
list, 289 for, 34, 193
string, 101 from..import, 68
slope of line, 63 if, 167
snowman, 96 if-elif-else, 176
software, 2 if-else, 173
software development, 21 import, 50
phases input, 13, 30
multiple input, 33
analysis, 21 print, 8, 27
design, 22 return, 148
implementation, 22 simultaneous assignment, 32
maintenance, 22 try-except, 178
specifications, 21 while, 195
testing/debugging, 22 stats.py, 292
sort StatSet, 320
stable, 313 stdDev, 290
sorting, 362 step-wise refinement, 235
merge sort str, 119
algorithm, 373 string, 99
analysis, 376 as lookup table, 104
implementation, 375 ASCII encoding, 108
selection sort concatenation, 27, 101
algorithm, 371 converting to, 119
analysis, 375 converting to other types, 112
implementation, 372 definition of, 25
space formatting, 121, see string formatting
between program lines, 39 indexing, 100
blank line in output, 146
in expressions, 26 from back, 101
in prompts, 31 length, 102
specifications, 21 literal, 100, 265
speeding fine, 189 methods, 111

Index 405

multi-line, 265 testing, 22
operators, 102 unit, 237
repetition, 102
representation, 107 Text, 91
slicing, 101 as prompt, 86
substring, 101 methods, 91
Unicode encoding, 108
vs. list, 286 text file, 125
string formatting text2numbers.py, 109
leading zeroes, 124 textpoker.py, 341
string method Three Button Monte, 278
lower, 129 Tkinter, 66
string formatting, 121 top-down design, 225
examples, 122
format specifier, 122 steps in process, 235
string library Towers of Hanoi (Brahma), 378
function summary, 114
split, 111 recursive solution, 380
structure chart, 227 Tracker, 281
structure charts triangle
racquetball simulation level 2, 230
racquetball simulation level 3, 232 area formula, 63
racquetball simulation top level, 228 program, 85, 148
Student triangle.pyw, 85
class, 259 triangle2.py, 148
subprogram, 139 truth table, 205
substitution cipher, 116 truth tables
substring, 101 definition of and, 205
swap, 32 definition of not, 205
using simultaneous assignment, 33 definition of or, 205
syntax, 5, 27 try-except statement
Syracuse numbers, 217 semantics, 178
syntax, 178
table tennis, 243 tuple, 303
table-driven, 299 unpacking, 303
temperature conversion turing.py, 383
type conversion
program, 166 automatic, 57
temperature conversion type conversion
to float, 57
algorithm, 23 explicit, 57
problem description, 22 from string, 112
program, 23 summary of functions, 120
program with GUI, 86 to int, 57
temperature conversion with warnings to string, 119
design, 166 type function, 46
flowchart, 166
problem description, 166 undraw, 89
program, 167 Unicode, 108
tennis, 243 unit testing, 237
unpacking, 303
userfile.py, 128
username generation

406 Index

program, 103, 128
username.py, 103

validation
of inputs, 208

value returning function, 148
ValueError, 51
variable

changing value, 29
definition of, 13
instance, 71, 247
local, 144
scope, 144
VGA, 76
volleyball, 206, 243

wc, 135
while statement

as post-test loop, 209
flow chart, 196
semantics, 195
syntax, 195
whitespace, see space
widget, 84, 267
windchill, 217
winter, 96
word count, 135
word frequency
problem description, 310
program, 313
word jumble, 391
wordfreq.py, 313
write, 128


Click to View FlipBook Version