0% found this document useful (0 votes)
3 views

Discovering Computer Science Interdisciplinary Problems Principles And Python Programming 2nd Edition Jessen Havill instant download

The document provides information about the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published in 2021. It includes details about the book's content, structure, and various chapters covering topics like problem-solving, data abstraction, and data analysis. Additionally, it offers links to download the book and other related resources.

Uploaded by

vwijcktplu4561
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Discovering Computer Science Interdisciplinary Problems Principles And Python Programming 2nd Edition Jessen Havill instant download

The document provides information about the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published in 2021. It includes details about the book's content, structure, and various chapters covering topics like problem-solving, data abstraction, and data analysis. Additionally, it offers links to download the book and other related resources.

Uploaded by

vwijcktplu4561
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Discovering Computer Science Interdisciplinary

Problems Principles And Python Programming 2nd


Edition Jessen Havill download

https://ebookbell.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-2nd-
edition-jessen-havill-24229672

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming Havill

https://ebookbell.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-
havill-21354402

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming 1st Edition Jessen Havill

https://ebookbell.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-1st-
edition-jessen-havill-5743478

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming First Edition Jessen Havill

https://ebookbell.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-first-
edition-jessen-havill-10833944

Discovering Computer Science Havill Jessen

https://ebookbell.com/product/discovering-computer-science-havill-
jessen-61266728
Computer Science Notable Research And Discoveries Kyle Kirkland

https://ebookbell.com/product/computer-science-notable-research-and-
discoveries-kyle-kirkland-23139084

Discovering Computers Fundamentals Your Interactive Guide To The


Digital World Gary B Shelly

https://ebookbell.com/product/discovering-computers-fundamentals-your-
interactive-guide-to-the-digital-world-gary-b-shelly-2412418

Discovering Computers Fundamentals 2011 Edition Shelly Cashman 7th


Edition Gary B Shelly

https://ebookbell.com/product/discovering-computers-
fundamentals-2011-edition-shelly-cashman-7th-edition-gary-b-
shelly-2414214

Discovering Computers Complete Your Interactive Guide To The Digital


World 1st Edition Gary B Shelly

https://ebookbell.com/product/discovering-computers-complete-your-
interactive-guide-to-the-digital-world-1st-edition-gary-b-
shelly-2446660

Discovering Computers Fundamentals 5th Ed Gary B Shelly Misty E


Vermaat Contributing Authors

https://ebookbell.com/product/discovering-computers-fundamentals-5th-
ed-gary-b-shelly-misty-e-vermaat-contributing-authors-2620866
Discovering Computer Science
Chapman & Hall/CRC
Textbooks in Computing
Series Editors
John Impagliazzo
Andrew McGettrick

Pascal Hitzler, Markus Krötzsch, and Sebastian Rudolph, Foundations of Semantic Web Technologies
Henrik Bærbak Christensen, Flexible, Reliable Software: Using Patterns and Agile Development
John S. Conery, Explorations in Computing: An Introduction to Computer Science
Lisa C. Kaczmarczyk, Computers and Society: Computing for Good
Mark Johnson, A Concise Introduction to Programming in Python
Paul Anderson, Web 2.0 and Beyond: Principles and Technologies
Henry Walker, The Tao of Computing, Second Edition
Ted Herman, A Functional Start to Computing with Python
Mark Johnson, A Concise Introduction to Data Structures Using Java
David D. Riley and Kenny A. Hunt, Computational Thinking for the Modern Problem Solver
Bill Manaris and Andrew R. Brown, Making Music with Computers: Creative Programming in Python
John S. Conery, Explorations in Computing: An Introduction to Computer Science and Python Programming
Jessen Havill, Discovering Computer Science: Interdisciplinary Problems, Principles, and Python
Programming
Efrem G. Mallach, Information Systems: What Every Business Student Needs to Know
Iztok Fajfar, Start Programming Using HTML, CSS, and JavaScript
Mark C. Lewis and Lisa L. Lacher, Introduction to Programming and Problem-Solving Using Scala,
Second Edition
Aharon Yadin, Computer Systems Architecture
Mark C. Lewis and Lisa L. Lacher, Object-Orientation, Abstraction, and Data Structures Using Scala,
Second Edition
Henry M. Walker, Teaching Computing: A Practitioner’s Perspective
Efrem G. Mallach, Information Systems:What Every Business Student Needs to Know, Second Edition
Jessen Havill, Discovering Computer Science: Interdisciplinary Problems, Principles, and Python
Programming, Second Edition
For more information about this series please visit:
https://www.crcpress.com/Chapman--HallCRC-Textbooks-in-Computing/book-series/CANDHTEXCO
MSER?page=2&order=pubdate&size=12&view=list&status=published,forthcoming
Discovering Computer Science
Interdisciplinary Problems, Principles, and
Python Programming
Second Edition

Jessen Havill
Second edition published 2021
by CRC Press
2 Park Square, Milton Park, Abingdon, Oxon, OX14 4RN

and by CRC Press


6000 Broken Sound Parkway NW, Suite 300, Boca Raton, FL 33487-2742

© 2021 Jessen Havill

The right of Jessen Havill to be identified as author of this work has been asserted by him in accordance with sections
77 and 78 of the Copyright, Designs and Patents Act 1988.

All rights reserved. No part of this book may be reprinted or reproduced or utilised in any form or by any electronic,
mechanical, or other means, now known or hereafter invented, including photocopying and recording, or in any infor­
mation storage or retrieval system, without permission in writing from the publishers.

For permission to photocopy or use material electronically from this work, access www.copyright.com or contact the
Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923, 978-750-8400. For works that are
not available on CCC please contact mpkbookspermissions@tandf.co.uk

Trademark notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.

British Library Cataloguing-in-Publication Data


A catalogue record for this book is available from the British Library

Library of Congress Cataloging-in-Publication Data

Names: Havill, Jessen, author.


Title: Discovering computer science : interdisciplinary problems,
principles, and Python programming / Jessen Havill.
Description: Second edition. | Boca Raton : CRC Press, 2021. | Series:
Chapman & Hall/CRC press textbooks in computing | Includes
bibliographical references and index.
Identifiers: LCCN 2020030144 | ISBN 9780367472498 (paperback) | ISBN
9780367613358 (hardback) | ISBN 9781003037149 (ebook)
Subjects: LCSH: Computer science--Textbooks. | Python (Computer program
language)--Textbooks.
Classification: LCC QA76 .H3735 2021 | DDC 005.13/3--dc23
LC record available at https://lccn.loc.gov/2020030144

ISBN: 9780367613358 (hbk)


ISBN: 9780367472498 (pbk)
ISBN: 9781003037149 (ebk)

Typeset in Computer Modern font


by Cenveo Publisher Services
Contents

Preface xv

Acknowledgments xxiii

About the author xxv

Chapter 1 ∎ How to Solve It 1


1.1 UNDERSTAND THE PROBLEM 3
A first problem: computing reading level 4
Functional abstraction 5
1.2 DESIGN AN ALGORITHM 6
Take it from the top 7
Pseudocode 10
Implement from the bottom 14
1.3 WRITE A PROGRAM 23
Welcome to the circus 23
What’s in a name? 28
Interactive computing 31
Looking ahead 32
1.4 LOOK BACK 36
Testing 37
Algorithm efficiency 39
1.5 SUMMARY AND FURTHER DISCOVERY 45

Chapter 2 ∎ Visualizing Abstraction 49


2.1 DATA ABSTRACTION 51
Turtle graphics 53
2.2 DRAWING FLOWERS AND PLOTTING EARTHQUAKES 55
Iteration 57
Tangent 2.1 Defining colors 60

v
vi • Contents

Data visualization 62
2.3 FUNCTIONAL ABSTRACTION 66
Function parameters 69
2.4 PROGRAMMING IN STYLE 77
Program structure 78
Documentation 79
Tangent 2.2 Global variables 80
Self-documenting code 83
2.5 A RETURN TO FUNCTIONS 87
The math module 88
Writing functions with return values 89
Return vs. print 92
2.6 SCOPE AND NAMESPACES 97
Local namespaces 98
The global namespace 101
2.7 SUMMARY AND FURTHER DISCOVERY 105

Chapter 3 ∎ Inside a Computer 107


3.1 COMPUTERS ARE DUMB 108
Tangent 3.1 High performance computing 109
Machine language 111
Tangent 3.2 Byte code 112
3.2 EVERYTHING IS BITS 112
Bits are switches 112
Bits can represent anything 113
Tangent 3.3 Hexadecimal notation 114
Computing with bits 114
3.3 COMPUTER ARITHMETIC 118
Limited precision 118
Tangent 3.4 Floating point notation 120
Error propagation 120
Division 121
Complex numbers 122
*3.4 BINARY ARITHMETIC ***
More limited precision

*
Sections with *** in lieu of a page number are available on the book website.
Contents • vii

Negative integers
Designing an adder
Implementing an adder
3.5 THE UNIVERSAL MACHINE 124
3.6 SUMMARY AND FURTHER DISCOVERY 126

Chapter 4 ∎ Growth and Decay 129


4.1 ACCUMULATORS 130
Managing a fishing pond 130
Measuring network value 136
Organizing a concert 139
4.2 DATA VISUALIZATION 150
4.3 CONDITIONAL ITERATION 155
When will the fish disappear? 155
When will your nest egg double? 157
*4.4 CONTINUOUS MODELS ***
Difference equations
Radiocarbon dating
Tradeoffs between accuracy and time
Simulating an epidemic
*4.5 NUMERICAL ANALYSIS ***
The harmonic series
Approximating π
Approximating square roots
4.6 SUMMING UP 161
Tangent 4.1 Triangular numbers 163
4.7 FURTHER DISCOVERY 164
*4.8 PROJECTS ***
4.1 Parasitic relationships
4.2 Financial calculators
4.3 Market penetration
4.4 Wolves and moose

Chapter 5 ∎ Forks in the Road 165


5.1 RANDOM WALKS 166
Tangent 5.1 Interval notation 167
One small step 167
viii • Contents

Monte Carlo simulation 171


*5.2 PSEUDORANDOM NUMBER GENERATORS ***
Implementation
Testing randomness
*5.3 SIMULATING PROBABILITY DISTRIBUTIONS ***
The central limit theorem
5.4 BACK TO BOOLEANS 180
Predicate functions 182
Short circuit evaluation 183
DeMorgan’s laws 184
Thinking inside the box 187
Many happy returns 192
5.5 DEFENSIVE PROGRAMMING 199
Checking parameters 199
Assertions 202
Unit testing 204
Tangent 5.2 Unit testing frameworks 205
Testing floats 207
Catching exceptions 207
5.6 GUESS MY NUMBER 210
Ending the game nicely 212
Friendly hints 213
A proper win/lose message 214
5.7 SUMMARY AND FURTHER DISCOVERY 219
*5.8 PROJECTS ***
5.1 The magic of polling
5.2 Escape!

Chapter 6 ∎ Text, Documents, and DNA 221


6.1 FIRST STEPS 222
Normalization 223
Tangent 6.1 Natural language processing 224
Tokenization 228
Creating your own module 232
Testing your module 233
6.2 TEXT DOCUMENTS 238
Contents • ix

Reading from text files 239


Writing to text files 242
Reading from the web 243
6.3 ENCODING STRINGS 246
Computing checksums 246
Unicode 247
Tangent 6.2 Compressing text files 250
Indexing and slicing 251
6.4 A CONCORDANCE 256
Finding a word 257
A concordance entry 262
A complete concordance 263
6.5 WORD FREQUENCY TRENDS 266
Finding the frequency of a word 268
Getting the frequencies in slices 269
Plotting the frequencies 270
6.6 COMPARING TEXTS 272
Dot plots 274
*6.7 TIME COMPLEXITY ***
Best case vs. worst case
Asymptotic time complexity
*6.8 COMPUTATIONAL GENOMICS ***
A genomics primer
Basic DNA analysis
Transforming sequences
Comparing sequences
Reading sequence files
6.9 SUMMARY AND FURTHER DISCOVERY 281
*6.10 PROJECTS ***
6.1 Polarized politics
6.2 Finding genes

Chapter 7 ∎ Data Analysis 285


7.1 SUMMARY STATISTICS 286
Mean and variance 286
Minimum and maximum 288
x • Contents

7.2 WRANGLING DATA 293


Smoothing data 294
A more efficient algorithm 295
Modifying lists in place 297
List operators and methods 302
*List comprehensions 305
Tangent 7.1 NumPy arrays 306
7.3 TALLYING FREQUENCIES 310
Word frequencies 310
Dictionaries 311
Tangent 7.2 Hash tables 315
Finding the most frequent word 315
Bigram frequencies 317
Tangent 7.3 Sentiment analysis 318
7.4 READING TABULAR DATA 325
Earthquakes 326
*7.5 DESIGNING EFFICIENT ALGORITHMS ***
Removing duplicates
A first algorithm
A more elegant algorithm
A more efficient algorithm
*7.6 LINEAR REGRESSION ***
*7.7 DATA CLUSTERING ***
Defining similarity
A simple example
Implementing k-means clustering
Locating bicycle safety programs
7.8 SUMMARY AND FURTHER DISCOVERY 333
Tangent 7.4 Privacy in the age of big data 334
*7.9 PROJECTS ***
7.1 Climate change
7.2 Does education influence unemployment?
7.3 Maximizing profit
7.4 Admissions
7.5 Preparing for a 100-year flood
7.6 Voting methods
Contents • xi

7.7 Heuristics for traveling salespeople

Chapter 8 ∎ Flatland 335


8.1 TABULAR DATA 335
Reading a table of temperatures 336
Tangent 8.1 Pandas 339
8.2 THE GAME OF LIFE 342
Creating a grid 344
Initial configurations 345
Surveying the neighborhood 346
Performing one pass 347
Tangent 8.2 NumPy arrays in two dimensions 349
Updating the grid 349
8.3 DIGITAL IMAGES 353
Colors 353
Tangent 8.3 Additive vs. subtractive color models 354
Image filters 355
Tangent 8.4 Image storage and compression 356
Transforming images 358
8.4 SUMMARY AND FURTHER DISCOVERY 363
*8.5 PROJECTS ***
8.1 Modeling segregation
8.2 Modeling ferromagnetism
8.3 Growing dendrites
8.4 Simulating an epidemic

Chapter 9 ∎ Self-similarity and Recursion 365


9.1 FRACTALS 365
Trees 367
Snowflakes 369
9.2 RECURSION AND ITERATION 375
Solving a problem recursively 379
Palindromes 380
Guessing passwords 382
9.3 THE MYTHICAL TOWER OF HANOI 388
*Is the end of the world nigh? 390
9.4 RECURSIVE LINEAR SEARCH 392
xii • Contents

*Efficiency of recursive linear search 393


9.5 DIVIDE AND CONQUER 396
Buy low, sell high 397
Navigating a maze 400
*9.6 LINDENMAYER SYSTEMS ***
Formal grammars
L-systems
Implementing L-systems
9.7 SUMMARY AND FURTHER DISCOVERY 405
*9.8 PROJECTS ***
9.1 Lindenmayer’s beautiful plants
9.2 Gerrymandering
9.3 Percolation

Chapter 10 ∎ Organizing Data 407


10.1 BINARY SEARCH 408
Tangent 10.1 Databases 409
Efficiency of iterative binary search 412
A spelling checker 414
Recursive binary search 415
*Efficiency of recursive binary search 416
10.2 SELECTION SORT 418
Implementing selection sort 419
Efficiency of selection sort 422
Querying data 423
10.3 INSERTION SORT 427
Implementing insertion sort 428
Efficiency of insertion sort 430
10.4 EFFICIENT SORTING 433
Merge sort 433
Internal vs. external sorting 437
Efficiency of merge sort 437
*10.5 TRACTABLE AND INTRACTABLE ALGORITHMS ***
Hard problems
10.6 SUMMARY AND FURTHER DISCOVERY 441
*10.7 PROJECTS ***
Contents • xiii

10.1 Creating a searchable database


10.2 Binary search trees

Chapter 11 ∎ Networks 443


11.1 MODELING WITH GRAPHS 444
Making friends 446
11.2 SHORTEST PATHS 451
Breadth-first search 451
Finding the actual paths 455
11.3 IT’S A SMALL WORLD. . . 458
Small world networks 458
Clustering coefficients 459
Scale-free networks 461
11.4 RANDOM GRAPHS 464
11.5 SUMMARY AND FURTHER DISCOVERY 467
*11.6 PROJECTS ***
11.1 Diffusion of ideas and influence
11.2 Slowing an epidemic
11.3 The Oracle of Bacon

Chapter 12 ∎ Object-oriented Design 469


12.1 SIMULATING AN EPIDEMIC 470
Object design 471
Person class 472
Augmenting the Person class 477
World class 479
The simulation 481
12.2 OPERATORS AND POLYMORPHISM 486
Designing a Pair ADT 487
Pair class 488
Arithmetic methods 489
Special methods 491
Comparison operators 493
Indexing 494
*12.3 A FLOCKING SIMULATION ***
The World
Boids
xiv • Contents

*12.4 A STACK ADT ***


Stack class
Reversing a string
Converting numbers to other bases
*12.5 A DICTIONARY ADT ***
Hash tables
Implementing a hash table
Indexing
ADTs vs. data structures
12.6 SUMMARY AND FURTHER DISCOVERY 499
*12.7 PROJECTS ***
12.1 Tracking GPS coordinates
12.2 Economic mobility
12.3 Slime mold aggregation
12.4 Boids in space

Bibliography 501

Appendix A ∎ Python Library Reference ***

Appendix B ∎ Selected Exercise Solutions ***

Index 505
Preface

I nthree
my view, an introductory computer science course should strive to accomplish
things. First, it should demonstrate to students how computing has become
a powerful mode of inquiry, and a vehicle of discovery, in a wide variety of disciplines.
This orientation is also inviting to students of the natural and social sciences, and the
humanities, who increasingly benefit from an introduction to computational thinking,
beyond the limited “black box” recipes often found in manuals and “Computing
for X” books. Second, the course should engage students in computational problem
solving, and lead them to discover the power of abstraction, efficiency, and data
organization in the design of their solutions. Third, the course should teach students
how to implement their solutions as computer programs. In learning how to program,
students more deeply learn the core principles, and experience the thrill of seeing
their solutions come to life.
Unlike most introductory computer science textbooks, which are organized around
programming language constructs, I deliberately lead with interdisciplinary problems
and techniques. This orientation is more interesting to a more diverse audience, and
more accurately reflects the role of programming in problem solving and discovery.
A computational discovery does not, of course, originate in a programming language
feature in search of an application. Rather, it starts with a compelling problem which
is modeled and solved algorithmically, by leveraging abstraction and prior experience
with similar problems. Only then is the solution implemented as a program.
Like most introductory computer science textbooks, I introduce programming skills
in an incremental fashion, and include many opportunities for students to practice
them. The topics in this book are arranged to ease students into computational
thinking, and encourage them to incrementally build on prior knowledge. Each
chapter focuses on a general class of problems that is tackled by new algorithmic
techniques and programming language features. My hope is that students will leave
the course, not only with strong programming skills, but with a set of problem
solving strategies and simulation techniques that they can apply in their future work,
whether or not they take another computer science course.
I use Python to introduce computer programming for two reasons. First, Python’s
intuitive syntax allows students to focus on interesting problems and powerful
principles, without unnecessary distractions. Learning how to think algorithmically
is hard enough without also having to struggle with a non-intuitive syntax. Second,
the expressiveness of Python (in particular, low-overhead lists and dictionaries)
expands tremendously the range of accessible problems in the introductory course.

xv
xvi • Preface

Teaching with Python over the last fifteen years has been a revelation; introductory
computer science has become fun again.

Changes in the second edition


In this comprehensive, cover-to-cover update, some sections were entirely rewritten
while others saw only minor revisions. Here are the highlights:

Problem solving The new first chapter, How to Solve It, sets the stage by focusing on
Polya’s elegant four-step problem solving process, adapted to a computational frame­
work. I introduce informal pseudocode, functional decomposition, hand-execution
with informal trace tables, and testing, practices that are now carried on throughout
the book. The introduction to Python (formally Chapter 2) is integrated into this
framework. Chapter 7, Designing Programs, from the first edition has been elimi­
nated, with that material spread out more naturally among Chapters 1, 5, and 6 in
the second edition.
Chapter 2, Visualizing Abstraction (based on the previous Chapter 3), elaborates on
the themes in Chapter 1, and their implementations in Python, introducing turtle
graphics, functions, and loops. The new Chapter 3, Inside a Computer (based on
the previous Sections 1.4 and 2.5), takes students on a brief excursion into the simple
principles underlying how computers work.

Online materials To reduce the size of the printed book, we have moved some
sections and all of the projects online. These sections are marked in the table of
contents with ***. Online materials are still indexed in the main book for convenience.

Exercises I’ve added exercises to most sections, bringing the total to about 750.
Solutions to exercises marked with an asterisk are available online for both students
and self-learners.

Digital humanities The interdisciplinary problems in the first edition were focused
primarily in the natural and social sciences. In this edition, especially in Chapters 1,
6, and 7, we have added new material on text analysis techniques commonly used in
the “digital humanities.”

Object-oriented design Chapter 12 begins with a new section to introduce object-


oriented design in a more concrete way through the development of an agent-based
simulation of a viral epidemic. The following sections flesh out more details on how
to implement polymorphic operators and collection classes.
Preface • xvii

Book website
Online materials for this book are available at

https://www.discoveringCS.net.
Here you will find

• additional “optional” sections, marked with an asterisk in the main text,


• over thirty interdisciplinary programming projects,
• solutions to selected exercises,
• programs and data files referenced in the text, exercises, and projects, and
• pointers for further exploration and links to additional documentation.

To students
Active learning Learning how to solve computational problems and implement
them as computer programs requires daily practice. Like an athlete, you will get
out of shape and fall behind quickly if you skip it. There are no shortcuts. Your
instructor is there to help, but he or she cannot do the work for you.
With this in mind, it is important that you type in and try the examples throughout
the text, and then go beyond them. Be curious! There are numbered “Reflection”
questions throughout the book that ask you to stop and think about, or apply,
something that you just read. Often, the question is answered in the book immediately
thereafter, so that you can check your understanding, but peeking ahead will rob
you of an important opportunity.

Further discovery There are many opportunities to delve into topics more deeply.
“Tangent” boxes scattered throughout the text briefly introduce related, but more
technical or applied, topics. For the most part, these are not strictly required to
understand what comes next, but I encourage you to read them anyway. In the
“Summary and Further Discovery” section of each chapter, you can find both a
high-level summary of the chapter and additional pointers to explore chapter topics
in more depth.

Exercises and projects At the end of most sections are several programming exercises
that ask you to further apply concepts from that section. Often, the exercises assume
that you have already worked through all of the examples in that section. Solutions
to the starred exercises are available on the book website. There are also more
involved projects available on the book website that challenge you to solve a variety
of interdisciplinary problems.

No prerequisites The book assumes no prior knowledge of computer science. How­


ever, it does assume a modest comfort with high school algebra. In optional sections,
xviii • Preface

trigonometry is occasionally mentioned, as is the idea of convergence to a limit, but


these are not relevant to understanding the main topics in the book.

Have fun! Programming and problem solving should be a fun, creative activity. I
hope that this book sparks your curiosity and love of learning, and that you enjoy
the journey as much as I have enjoyed writing this book.

To instructors
This book is appropriate for a traditional CS1 course for majors, a CS0 course for
non-majors (at a slower pace and omitting more material), or a targeted introductory
computing course for students in the natural sciences, social sciences, or humanities.
The approach is gentle and holistic, introducing programming concepts in the context
of interdisciplinary problems. We start with problem-solving, featuring pseudocode
and hand-execution with trace tables, and carry these techniques forward, especially
in the first half of the book.

Problem focus Most chapters begin with an interesting problem, and new concepts
and programming techniques are introduced in the context of solving it. As new
techniques are introduced, students are frequently challenged to re-solve old problems
in different ways. They are also encouraged to reuse their previous functions as
components in later programs.

Reflection questions, exercises, and projects “Reflection” questions are embedded


in every section to encourage active reading. These may also be assigned as “reading
questions” before class. The end-of-section exercises are appropriate for regular home­
work, and some more complex ones may form the basis of longer-term assignments.
The book website also hosts a few dozen interdisciplinary projects that students may
work on independently or in pairs over a longer time frame. I believe that projects
like these are crucial for students to develop both problem solving skills and an
appreciation for the many fascinating applications of computer science.

Additional instructor resources All of the reflection questions and exercises are
available to instructors as Jupyter notebooks. Solutions to all exercises and projects
are also available. Please visit the publisher’s website to request access.

Python coverage This book is not intended to be a Python manual. Some features
of the language were intentionally omitted because they would have muddled the core
problem solving focus or are not commonly found in other languages that students
may see in future CS courses (e.g., simultaneous swap, chained comparisons, zip,
enumerate in for loops).

Topic coverage There is more in this book than can be covered in a single semester,
giving instructors the opportunity to tailor the content to their particular situation
Preface • xix

Chapter 2 Chapter 3 Chapter 4


Chapter 1
Visualizing Inside a Growth and
How to Solve It
Abstraction Computer Decay

Chapter 6
Chapter 7 Chapter 5
Text, Documents,
Data Analysis Forks in the Road
and DNA

Chapter 9
Chapter 8 Chapter 10
Self-similarity and
Flatland Organizing Data
Recursion

Chapter 12
Chapter 11
Object-oriented
Networks
Design

Figure 1 An overview of chapter dependencies.

and interests. As illustrated in Figure 1, Chapters 1–7 form the core of the book, and
should be covered sequentially. The remaining chapters can be covered, partially or
entirely, at your discretion, although I would expect that most instructors will cover
at least parts of Chapters 8–10, and 12 if the course covers object-oriented design.
Chapter 11 introduces social network graphs and small-world and scale-free networks
as additional powerful applications of dictionaries, and may come any time after
Chapter 7. Sections marked with an asterisk are optional, in the sense that they are
not assumed for future sections in that chapter. When exercises and projects depend
on optional sections, they are also marked with an asterisk, and the dependency is
stated at the beginning of the project.

Chapter outlines The following tables provide brief overviews of what is available
in each chapter. Each table’s three columns, reflecting the three parts of the book’s
subtitle, provide three lenses through which to view the chapter.

1 How to Solve It
Sample problems Principles Programming
● reading level ● problems, input/output ● int, float, str types
● counting syllables, words ● functional abstraction ● arithmetic
● sphere volume ● functional decomposition ● assignment

● digital music ● top-down design ● variable names

● search engines ● bottom-up implementation ● calling built-in functions

● GPS devices ● algorithms and programs ● using strings

● phone trees ● pseudocode ● string operators

● wind chill ● names as references ● print and input

● compounding interest ● trace tables


● Mad Libs ● constant- vs. linear-time
xx • Preface

2 Visualizing Abstraction

Sample problems Principles Programming


● visualizing earthquakes ● using abstract data types ● using classes and objects
● drawing flowers ● creating functional ● turtle module
● random walks abstractions ● for loops (range and lists)
● ideal gas ● functional decomposition ● using and writing functions
● groundwater flow ● bottom-up implementation ● return vs. print

● demand functions ● turtle graphics ● namespaces and scope


● reading level ● trace tables with loops ● docstrings and comments
● self-documenting code
● program structure

3 Inside a Computer

Principles Programming
● computer organization ● int and float types
● machine language ● arithmetic errors
● binary representations ● true vs. floor division
● computer arithmetic
● finite precision, error propagation
● Boolean logic, truth tables, logic gates

● Turing machines, finite state machines

4 Growth and Decay

Sample problems Principles Programming


● population models ● accumulators ● for loops, range
● network value ● list accumulators ● format strings
● demand and profit ● data visualization ● matplotlib.pyplot

● loans and investing ● conditional iteration ● appending to lists


● bacterial growth ● classes of growth ● while loops
● radiocarbon dating ● continuous models
● epidemics (SIR, SIS) ● accuracy vs. time
● diffusion models ● numerical approximation

5 Forks in the Road


Sample problems Principles Programming
● random walks ● random number generators ● random module
● Monte Carlo simulation ● simulating probabilities ● if/elif/else
● guessing games ● flag variables ● comparison operators
● polling and ● using distributions ● Boolean operators

sampling ● DeMorgan’s laws ● short circuit evaluation

● particle escape ● defensive programming ● predicate functions


● pre- and post-conditions ● assert, isinstance

● unit testing ● catching exceptions


● histograms
● while loops
Preface • xxi

6 Text, Documents, and DNA


Sample problems Principles Programming
● text analysis ● functional decomposition ● str class and methods
● word frequency trends ● unit testing ● iterating over strings, lists
● checksums ● ASCII, Unicode ● indexing and slicing

● concordances ● linear-time algorithms ● iterating over indices


● dot plots, plagiarism ● time complexity ● creating a module
● congressional votes ● linear search ● text files and the web
● genomics ● string accumulators ● break
● nested loops

7 Data Analysis

Sample problems Principles Programming


● word, bigram frequencies ● histograms ● list class
● smoothing data ● hash tables ● indexing and slicing
● 100-year floods ● tabular data files ● list operators and methods
● traveling salesman ● efficient algorithm design ● reading CSV files
● meteorite sites ● linear regression ● modifying lists in place
● zebra migration ● k-means clustering ● list parameters
● tumor diagnosis ● heuristics ● tuples
● supply and demand ● list comprehensions
● voting methods ● dictionaries

8 Flatland
Sample problems Principles Programming
● earthquake data ● 2-D data ● lists of lists
● Game of Life ● cellular automata ● nested loops
● image filters ● digital images ● 2-D data in a dictionary

● racial segregation ● color models


● ferromagnetism
● dendrites
● epidemics
● tumor growth

9 Self-similarity and Recursion

Sample problems Principles Programming


● fractals ● self-similarity ● writing recursive functions
● cracking passwords ● recursion ● divide and conquer
● Tower of Hanoi ● linear search ● backtracking
● maximizing profit ● recurrence relations
● navigating a maze ● divide and conquer

● Lindenmayer systems ● depth-first search


● gerrymandering ● grammars
● percolation
xxii • Preface

10 Organizing Data

Sample problems Principles Programming


● spell check ● binary search ● nested loops
● querying data sets ● quadratic-time sorting ● writing recursive functions
● parallel lists
● merge sort
● recurrence relations

● intractability, P=NP?

11 Networks
Sample problems Principles Programming
● social media, web graphs ● graphs ● dictionaries
● diffusion of ideas ● adjacency list, matrix
● epidemics ● breadth-first search

● Oracle of Bacon ● queues


● shortest paths
● depth-first search
● small-world networks
● scale-free networks

● uniform random graphs

12 Object-oriented Design

Sample problems Principles Programming


● epidemic simulation ● abstract data types ● object-oriented design
● data sets ● encapsulation ● writing classes
● genomic sequences ● polymorphism ● special methods

● rational numbers ● data structures ● overriding operators


● flocking behavior ● stacks ● modules
● slime mold aggregation ● hash tables
● agent-based simulation
● swarm intelligence

Software assumptions
To follow along in this book and complete the exercises, you will need to have
installed Python 3.6 or later on your computer, and have access to IDLE or another
programming environment. The book also assumes that you have installed the
matplotlib.pyplot and numpy modules. The easiest way to get this software is to
install the free open source Anaconda distribution from http://www.anaconda.com.

Errata
While I (and my students) have ferreted out many errors, readers will inevitably find
more. You can find an up-to-date list of errata on the book website. If you find an error
in the text or have another suggestion, please let me know at havill@denison.edu.
Acknowledgments

In addition to those who provided their support and expertise for the first edition,
I wish to thank Janet Davis (Whitman College), Jim Deverick (The College of
William and Mary), David Goodwin (Denison University), and Ashwin Lall (Denison
University) for their valuable feedback on drafts of the second edition.
I would also like to thank Dee Ghiloni, Mary Lucas-Miller, and Tony Silveira for
their steadfast support, Mike Brady and my Data Analytics colleagues for reminding
me how much fun it can be to learn new things, and the Book Group for reminding
me to not take life too seriously. A Bowen Fellowship awarded by Denison University
gave me the time needed to complete this project.
Finally, my family has once again provided me with seemingly infinite patience and
love during this intensive period of writing. I am an extraordinarily lucky husband
and father.

xxiii
About the author

Jessen Havill is a Professor of Computer Science at Denison University. He has


been teaching courses across the computer science curriculum for almost thirty years,
and was awarded the College’s highest teaching honor, the Charles A. Brickman
Teaching Excellence Award, in 2013. Although his primary expertise is in the
development and analysis of online algorithms, Dr. Havill has spent many years
collaborating with colleagues across the curriculum to develop interdisciplinary
academic opportunities for students. From 2016–2019, he became the founding
Director of Denison University’s interdisciplinary Data Analytics program. Dr. Havill
earned his bachelor’s degree from Bucknell University and his Ph.D. in computer
science from The College of William and Mary.

xxv
CHAPTER 1

How to Solve It

We need to do away with the myth that computer science is about computers. Computer
science is no more about computers than astronomy is about telescopes, biology is about
microscopes or chemistry is about beakers and test tubes. Science is not about tools, it is
about how we use them and what we find out when we do.

Michael R. Fellows and Ian Parberry


Computing Research News (1993)

It has often been said that a person does not really understand something until after teaching
it to someone else. Actually a person does not really understand something until after
teaching it to a computer, i.e., expressing it as an algorithm.

Donald E. Knuth
American Scientist (1973)

C consciously
omputers now touch almost every facet of our daily lives, whether we are
aware of them or not. Computers have changed the way we learn,
communicate, shop, travel, receive healthcare, and entertain ourselves. They are
embedded in virtually everything, from major feats of engineering like airplanes,
spaceships, and factories to everyday items like microwaves, cameras, and tooth­
brushes. In addition, all of our critical infrastructure—utilities, transportation,
finance, communication, healthcare, law enforcement—relies upon computers.
Since computers are the most versatile tools ever invented, it should come as
no surprise that they are also employed throughout academia in the pursuit of
new knowledge. Social scientists use computational models to better understand
social networks, epidemics, population dynamics, markets, and auctions. Humanists
use computational tools to gain insight into literary trends, authorship of ancient
texts, and the macroscopic significance of historical records. Artists are increasingly
incorporating digital technologies into their compositions and performances. Natural

1
2 • 1 How to Solve It

Look back at
Understand the Design an Write a
your algorithm
problem algorithm program
and results

Figure 1.1 A simplified view of the problem solving process.

scientists use computers to collect and analyze immense quantities of data to


make discoveries in environmental science, genomics, particle physics, neuroscience,
pharmacology, and medicine.
But computers are neither productive nor consequential on their own. All of the
computers now driving civilization, for good or ill, were taught by humans. Computers
are amplifiers of human ingenuity. Without us, they are just dumb machines.
The goal of this book is to empower you to teach computers to solve problems and
make discoveries. Computational problem solving is a process that you will find both
familiar and new. We all solve problems every day and employ a variety of strategies
in doing so. Some of these strategies, like breaking big problems into smaller, more
manageable ones, are also fundamental to solving problems with a computer. Where
computational problem solving is different stems from computers’ lack of intellect
and intuition. Computers will only do what you tell them to and nothing more.
They cannot tolerate ambiguity or intuit your intentions. Computational problem
solving, by necessity, must be more precise and intentional than you may be used to.
The payoff though, paraphrasing Donald Knuth1 , is that teaching a computer to do
something can also dramatically deepen our understanding of that thing.
The problem solving process that we will outline in this chapter is inspired by How to
Solve It, a short book written by mathematician George Polya [50] in 1945. Polya’s
problem solving framework, having withstood the test of time, consists of four steps:

1. First, understand the problem. What is the unknown? What are the data?
What is the condition?
2. Second, devise a plan to solve the problem.
3. Third, carry out your plan, checking each step.
4. Fourth, look back. Check the result. Can you derive the result differently?

These four steps, with some modifications, can be applied just as well to compu­
tational problem solving, as illustrated in Figure 1.1. In the first step, we make

1
You can learn more about Donald Knuth at the end of this chapter.
1.1 UNDERSTAND THE PROBLEM • 3

Figure 1.2 Some examples of computational problems.

sure that we understand the problem to be solved. In the second step, we devise an
algorithm, a sequence of steps to solve the problem. In the third step, we translate
our algorithm into a correct program that can be carried out by a computer. We
will be using a programming language called Python throughout this book to write
programs. Finally, in the fourth step, we look back on our results and ask whether
we can improve them or the algorithm that derived them. Notice that this process is
often not linear. Work on one step can refine our understanding of a previous step
and nudge us backward, not unlike the process of writing a paper.
This chapter serves as a framework for your learning throughout the rest of the book.
Each subsequent chapter will flesh out aspects of these steps and make them more
concrete by focusing on new types of computational problems and the techniques
used to solve them.

1.1 UNDERSTAND THE PROBLEM

First, understand the problem. What is the unknown? What are the data?
What is the condition?
In computer science, we think of a problem as a relationship between some initial
information, an input, and some desired result, the output. To solve the problem,
we need to teach a computer how to transform the input into the output. The steps
that the computer takes to do this are called a computation. In Polya’s language,
the “data” are the inputs, the “unknown” is the output, and the ”condition” is the
relationship between the two.
Figure 1.2 illustrates three common computational problems. In each, an input enters
on the left and a corresponding output exits on the right. In between, a computation
transforms the input into the correct output. When you listen to a song, your music
4 • 1 How to Solve It

player performs a computation to convert a digital sound file (input) into a sound
pattern that can be reproduced by your headphones (output). When you submit a
web search request (input), your computer, and many others across the Internet,
perform computations to get you results (outputs). And when you use an app on
your phone to get directions, it computes the directions (output) based on your
current position and desired destination (inputs).
Inputs and outputs are probably familiar to you from high school algebra. When
you were given an expression like y = 18x + 31 or f (x) = 18x + 31, you may have
thought about the variable x as a representation of the input and y, or f (x), as a
representation of the output. In this example, when the input is x = 2, the output is
y = 67, or f (x) = 67. The arithmetic that turns x into y is a very simple (and boring)
example of a computation.
Reflection 1.1 What kinds of problems are you interested in? What are their inputs and
outputs? Are the inputs and outputs, as you have defined them, sufficient to define the
problems completely?

A first problem: computing reading level


Suppose you are a teacher who wants to evaluate whether some text is at an
appropriate grade level for your class. In other words, you want to solve the problem
illustrated below.

reading level
text reading level
calculator

The input and output for this problem seem straightforward. But they actually
aren’t; once you start thinking carefully about the problem, you realize there are
many questions that need to be answered. For example, are there any restrictions
or special conditions associated with the input? What kinds of texts are we talking
about? Should the solution work equally well for children’s books, newspaper articles,
scientific papers, and technical manuals? For what language(s) should the solution
work? In what electronic format do the texts need to be? Is there a minimum or
maximum length requirement for the text? It is important to formulate these kinds
of questions and seek any needed clarifications right away; it is much better to do so
immediately than to wait until you have spent a lot of time working on the wrong
problem!
The same sorts of questions should be asked about the output. How is a reading
level represented? Is it an integer value corresponding to a school year? Or can it
be a fraction? To what educational system should the grade levels correspond? Are
their minimum and/or maximum allowed values? Once you have answers to your
questions, it is a good idea to re-explain the problem back to the poser, either orally
or in writing. The feedback you get from this exercise might identify additional points
of misunderstanding. You might also draw a picture and work out some examples by
hand to make sure you understand all of the requirements and subtleties involved.
1.1 UNDERSTAND THE PROBLEM • 5

We will answer these questions by clarifying that the solution should work for any
English language text, available as a plain text file like those on Project Gutenberg.2
The output will be a number like 4.2, indicating that the text is appropriate for
a student who has completed 2/10 of fourth grade in the U.S. educational system.
Negative reading level values will not make sense in this system, but any positive
number will be acceptable if we interpret the number to mean the number of years
of education required to understand the text.

Functional abstraction
A problem at this stage, before we know how to solve it, is an example of a functional
abstraction.
A functional abstraction describes how to use a tool or technology without
necessarily providing any knowledge about how it works.
In other words, a functional abstraction is a “black box” that we know how to
use effectively, without necessarily understand what is happening inside the box to
produce the output. In the case of the reading level problem, now that we have a
better handle on the specifics, if we had a black box that computed the reading
level, we would know how to use it, even without understanding how the output was
computed. Similarly, to use each of the technologies illustrated in Figure 1.2 we do
not need to understand how the underlying computation transforms the input to
the output.
We exist in a world of functional abstractions that we usually take for granted. We
even think about our own bodies in terms of abstractions. Move your fingers. Did
you need to understand how your brain triggered your nervous and musculoskeletal
systems to make that happen? As far as most of us are concerned, a car is also an
abstraction. To drive a car, do you need to know how turning the steering wheel turns
the car or pushing the accelerator makes it go faster? We understand what should
happen when we do these things, but not necessarily how they happen. Without
abstractions, we would be paralyzed by an avalanche of minutiae.
Reflection 1.2 Imagine that it was necessary to understand how your phone works in
order to use it. Or a car. Or a computer. How would this affect your ability to use these
technologies?
New technologies and automation have introduced new functional abstractions into
everyday life. Our food supply is a compelling example of this. Only a few hundred
years ago, our ancestors knew exactly where their food came from. Inputs of hard
work and suitable weather produced outputs of grain and livestock to sustain a
family. In modern times, we input money and get packaged food; the origins of our
food have become much more abstract.
2
Project Gutenberg (http://www.gutenberg.org) is a library of freely available classic literature
with expired U.S. copyrights. The books are available in a variety of formats, but we will be
interested in those in a plain text format like the version of Walden by Henry David Thoreau at
http://www.gutenberg.org/files/205/205-0.txt.
6 • 1 How to Solve It

Reflection 1.3 Think about a common functional abstraction that you use regularly,
such as your phone or a credit card. How has this functional abstraction changed over
time? Can you think of instances in which better functional abstractions have enhanced
our ability to use a technology?
Functional abstraction is a very important idea in computer science. In the next
section, we will demonstrate how more complex problems are solved by breaking
them into smaller functional abstractions that we can solve and then recombine into
a solution for the original problem.

Exercises
1.1.1. What is a problem in your life that you have to solve regularly? Define the
input and output of the problem well enough for someone else to propose an
algorithm to solve it. Here is an example.

Problem: scan pages in a book


Inputs: a book and page numbers to scan
Output: one PDF file containing all of the pages, one physical page per page
in the file, full color, text recognized
1.1.2. What information is missing from each of the inputs and/or outputs of the
following problem definitions? In each case, assume that you know how to
complete the task given enough information about the input and output.
(a)* Problem: Make brownies
Inputs: butter, sugar, eggs, vanilla, cocoa powder, flour, salt, baking powder
Output: brownies
(b) Problem: Dig a hole
Inputs: a shovel
Output: a hole (of course)
(c) Problem: Plant a vegetable garden
Inputs: seeds
Output: a planted garden plot
1.1.3. Describe three examples from your everyday life in which an abstraction is
beneficial. Explain the benefits of each abstraction versus what life would be
like without it.

1.2 DESIGN AN ALGORITHM

Second, devise a plan to solve the problem.

To compute reading level, we will use the well-known Flesch-Kincaid grade level
score, which approximates the grade level of a text using the formula

0.39 × average words per sentence + 11.8 × average syllables per word − 15.59 .
1.2 DESIGN AN ALGORITHM • 7

Reflection 1.4 To better understand how the Flesch-Kincaid grade level formula works,
apply it to the first epigraph (Fellows and Parberry) at the beginning of this chapter.
What does the formula output as the grade level of this quote?
The 3 sentences in the quote contain 14, 24, and 20 words, respectively, so the
average number of words per sentence is (14 + 24 + 20)/3 ≈ 19.33. There are 90 total
syllables in the quote’s 58 words, so the average number of syllables per word is
90/58 ≈ 1.55. Plugging these values into the formula, we get

0.39 × 19.33 + 11.8 × 1.55 − 15.59 ≈ 10.24.

So the formula says that the quote is at about a tenth grade reading level.
You may be surprised to hear that this formula does not provide nearly enough
detail for a computer to carry it out. You can figure out how to find the average
number of words per sentence and the average number of syllables per word, but a
computer definitely cannot without a lot more help. Instead, this formula is more
appropriately thought of as a more detailed description of what the output “reading
level” means.
To teach a computer how to apply the Flesch-Kincaid formula to any text, we need
to replace the black box with a detailed sequence of steps that transforms the input
(text) into the correct output (reading level). This sequence of steps is called an
algorithm. An algorithm is how we teach a computer how to solve a problem.

Take it from the top


To make designing an algorithm more manageable, we can decompose it into simpler
subproblems. A subproblem is an easier problem that, once solved, will make
solving the original problem more straightforward.
Reflection 1.5 Look at the Flesch-Kincaid formula again. What are the two subproblems
we need to solve before we can apply the formula?
As we saw when we applied the formula, we need to determine two things about the
text: the average number of words per sentence and the average number of syllables
per word. So these are two subproblems of the overall problem, together with the
actual calculation of the Flesch-Kincaid grade level score. We can represent this as
follows.

reading level
of a text

average number of average number of Flesch-Kincaid


words per sentence syllables per word grade level score

This diagram shows us that there are three subproblems involved in solving the
reading level problem. If we had functional abstractions, “black boxes,” for these
three subproblems, then we could easily solve the reading level problem by getting the
8 • 1 How to Solve It

President

Academic Finance and Student


Affairs Management Affairs

Natural Social Humanities Human Health and Residential


Budget Athletics
Sciences Sciences and Arts Resources Wellness Life

Computer Political Varsity


Biology … Sociology … History Music … Recreation Club Sports
Science Science Athletics

Figure 1.3 A simplified organizational chart of a hypothetical college.

required values from the two leftmost subproblems and then plugging their outputs
into the third subproblem. This technique is called top-down design because it
involves starting from the top, the problem to be solved, and then breaking it
down into smaller pieces. The final result of this process is called a functional
decomposition.
Top-down design and functional decomposition are commonly used to make all sorts
of things more manageable. For example, suppose you are the president of a college.
Because you cannot effectively manage every detail of such a large organization, you
hire a vice president to oversee each of three divisions, as illustrated in Figure 1.3.
You expect each vice president to keep you informed about the general activity
and performance of their division, but insulate you from the day-to-day details. In
this arrangement, each division becomes a functional abstraction to you; you know
what each division does, but not necessarily how it does it, freeing you to focus on
more important organization-level activity. Each vice president may utilize a similar
arrangement within their division. Indeed, organizations are often subdivided many
times until the number of employees in a unit is small enough to be overseen by a
single manager.
Similarly, each of the subproblems in a functional decomposition might be further
broken down, until we arrive at subproblems that are straightforward to solve.
Reflection 1.6 Can the left subproblem in the reading level problem, “average number
of words per sentence,” be computed directly? Or can it be decomposed further? (Think
about how you computed the reading level in Reflection 1.2.)

We saw above that the average number of words per sentence is equal to the total
number of words divided by the total number of sentences, so we can decompose
this subproblem into two even simpler subproblems:

average number of
words per sentence

total number of total number of


words sentences
1.2 DESIGN AN ALGORITHM • 9

reading level
of a text

average number of average number of Flesch-Kincaid


words per sentence syllables per word grade level score

total number of total number of total number of total number of


words sentences syllables words

number of syllables
in one word

Figure 1.4 Functional decomposition of the reading level problem.

Similarly, we can also decompose the problem of computing the average number of
syllables per word into two subproblems:

average number of
syllables per word

total number of total number of


syllables words

Taken altogether, we are now left with three relatively simple subproblems to solve:
(a) counting the total number of words, (b) counting the total number of sentences,
and (c) counting the total number of syllables.
Reflection 1.7 Can computing the total numbers of words, sentences, or syllables be
broken down further?
Counting the total numbers of words and sentences seems pretty straightforward.
But finding the total number of syllables is not as simple because even finding the
number of syllables in one word is not trivial for a computer, especially with all
of the oddities of the English language. Thus it makes sense to further decompose
finding the total number of syllables into the subproblem of finding the number of
syllables in just one word.
A diagram of the final functional decomposition is shown in Figure 1.4. These kinds
of diagrams are called trees because they resemble an upside down tree with the
root at the top and branches spreading out below. Nodes at the bottom of the tree
are called leaves.
10 • 1 How to Solve It

Pseudocode
The next step is to write an algorithm for each of the subproblems, starting with
the leaves at the bottom of the tree and working our way up to the root. We will get
to this shortly, but first let’s write an algorithm for a more straightforward problem.

Computing the volume of a sphere


This simple problem can be visualized as follows.

radius r sphere volume volume of a sphere with radius r

To compute the output from the input, we can simply use the well-known formula
V = (4/3)πr3 . Although this is much closer to an algorithm than the Flesch-Kincaid
formula, it still does not explicitly specify a sequence of steps; there are several
alternative sequences that one could follow to carry it out.3 For example, we could
cube r first, then multiply that result by the rest of the terms, or we could cube r
last, or we could multiply r by (4/3)π then by r2 , etc. Here is one algorithm that
follows the formula:

Algorithm Sphere Volume

Input: the radius r of the sphere


1 Multiply r × r × r.
2 Multiply the previous result by π.
3 Multiply the previous result by 4.
4 Divide the previous result by 3.
Output: the final result, which is the volume of the sphere

At the top of the algorithm, we note the input and at the bottom we note the output.
In between, the individual lines are called statements. Carrying out the sequence
of statements in an algorithm is called executing or running the algorithm.
The informal style in which this algorithm is written is known as pseudocode, to
differentiate it from code, which is another name for a computer program. In common
usage, the prefix pseudo often has a negative connotation, as in pseudo-intellectual
or pseudoscience, but here it simply connotes a relaxed manner of writing algorithms
that is meant to be read by a human rather than a computer. The flexibility afforded
by pseudocode allows us to more clearly focus on how to solve the problem at hand
without becoming distracted by the more demanding requirements of a programming
language. Once we have refined the algorithm adequately and convinced ourselves
that it is correct, we can translate it into a formal program. We’ll talk more about
that in the next section.

3
In Python, we can actually use this formula more or less directly, but to facilitate this simple
example, we’ll pretend otherwise for now.
1.2 DESIGN AN ALGORITHM • 11

Here is a different algorithm that also computes the volume of a sphere. We are
calling this algorithm a “draft” because, like other kinds of writing, algorithms also
require rounds of revisions. We will revise this algorithm two more times.

Algorithm Sphere Volume 2 — Draft 1

Input: the radius r of the sphere


1 Divide 4 by 3.
2 Multiply the previous result by π.
3 Repeat the following three times: multiply the previous result by r.
Output: the final result, which is the volume of the sphere

To better understand what an algorithm is doing, we can execute it on an example,


using a trace table. In a trace table, we trace through each step of the algorithm
and keep track of what is happening. The following trace table shows the execution
of our draft Sphere Volume 2 algorithm with input value r = 10.

Trace input: r = 10
Step Line Result Notes
1 1 1.3̄ 4 ÷ 3 = 1.3̄
2 2 4.186̄ multiplying the previous result (1.3̄) by π
3 3 41.86̄ multiplying the previous result (4.186̄) by 10
4 3 418.6̄ multiplying the previous result (41.86̄) by 10
5 3 4,186.6̄ multiplying the previous result (418.6̄) by 10
Output: 4,186.6
¯

The four columns keep track of the number of steps executed by the algorithm, the
line number in the algorithm being executed, the result after that line is executed,
and notes explaining what is happening in that line.
The first two steps are pretty self-explanatory. Then, because line 3 of the algorithm
instructs us to repeat something three times, line 3 is executed 3 times in the trace
table. A statement that repeats like this is called a loop. When algorithms contain
loops, the number of steps is not necessarily the same as the number of lines.
Because we will eventually want to translate our pseudocode algorithms into actual
code, it will be important to adhere to some important principles that will make
this translation easier. First, we must strive to eliminate any ambiguity from our
algorithms. In other words, the steps in an algorithm must never require creative
interpretation by a human being. As we will see in Section 3.1, computers are, at their
core, only able to perform very simple instructions like arithmetic and comparing two
numbers, and are incapable of creative inference. Second, the steps of an algorithm
must be executable by a computer. In other words, they must correlate to things
12 • 1 How to Solve It

a computer can actually do. The definition of executable will become clearer as we
learn more about programming.
These two requirements are not really unique to computer algorithms. For example,
we hope that new surgical techniques are unambiguously presented with references to
actual anatomy and real surgical tools. Likewise, when an architect designs a building,
they must use only available materials and be precise about their placement. And
when an author writes a novel, they must write to their audience, using appropriate
language and culturally familiar references.
By these standards, both of the previous algorithms are less than ideal in at least
two ways. First, references to the “previous result” are not precise and will not get
us very far in more complex algorithms where multiple intermediate values need to
be remembered. This kind of imprecision can easily lead to problematic ambiguity in
our algorithms. Second, in none of the steps did we explicitly state that we needed
to remember a result to be used later. When you executed the algorithms, you could
infer this necessity, but this is an example of the kind of ambiguity that we need to
avoid when writing algorithms for a computer.
To remedy these issues, algorithms use variables to give names to values that need
to be remembered later. To make our algorithms understandable to a human reader,
we will use descriptive variable names, unlike the single letter x and y variables
that are common in mathematics. In our pseudocode algorithms, we will indicate
variables in italics and assign a value to a variable with the notation

variable ← value
The left-facing arrow indicates that the value on the right is being assigned to the
variable on the left. For example, eggs ← 12 would assign the value 12 to the variable
named eggs. Using variables, the Sphere Volume 2 algorithm can be rewritten as
follows.

Algorithm Sphere Volume 2 — Draft 2

Input: the radius r of the sphere


1 volume ← 4 ÷ 3
2 volume ← previous value of volume × π
3 repeat the following three times:
4 volume ← previous value of volume × r
Output: the value of volume

In this version, we have also formatted the loop a little bit differently, indenting the
statement that is being repeated on a separate line (line 4). The statements that are
executed repeatedly by a loop are called the body of the loop. So line 4 is the body
of the loop that starts on line 3. The following trace table, again with input value r
= 10, illustrates how the revised algorithm works.
1.2 DESIGN AN ALGORITHM • 13

Trace input: r = 10
Step Line volume Notes
1 1 ¯
1.3 volume ← 4 ÷ 3 = 1.3¯
2 2 4.186̄ volume ← previous volume × π = 1.3̄ × 3.14 = 4.186̄
3 3 ” volume unaffected; execute line 4 three times
4 4 41.86̄ volume ← previous volume × r = 4.186̄ × 10 = 41.86̄
5 4 ¯
418.6 volume ← previous volume × r = 41.86̄ × 10 = 418.6̄
6 4 ¯
4,186.6 volume ← previous volume × r = 418.6¯ × 10 = 4,186.6¯
Output: volume = 4,186.6
¯

Notice that we have replaced the generic “Result” column with a column that keeps
track of the value of the introduced variable, which we named volume because it
will eventually be assigned the volume of the sphere. The first line of the trace table
shows that the variable named volume is assigned the result of dividing 4 by 3. In
line 2, the value of volume, which is now 1.3, ¯ is multiplied by π (which we truncate
to 3.14), and the result, which is 4.186̄, is assigned to volume. Notice how much less
ambiguous this is, compared to a reference to a “previous result.” Also note that
this assignment has overwritten the previous value of volume. Next, line 3 does not
do anything on its own; it just instructs us to repeat line 4 three times. (The “ditto”
marks indicate no change to volume.) Each execution of line 4 multiplies the value
of volume by 10, and overwrites the value of volume with this result. At the end,
volume corresponds to the value 4,186.6, ¯ which is output by the algorithm.
Reflection 1.8 Trace through the algorithm again with input value r = 5. Create a new
¯
trace table to show your progress. (The final answer should be 523.3.)

Let’s make one more refinement to our algorithm. In line 2 (and similarly in line 4),
the algorithm refers to the “previous value of” volume on the righthand side of the
assignment:
volume ← previous value of volume × π
We included this language for clarity, but it is not actually necessary; the statement
can be abbreviated to
volume ← volume × π .
In any assignment statement, the righthand side after the arrow must be evaluated
first, before the result of this evaluation is assigned to the variable on the lefthand
side. Therefore, when volume is referenced on the righthand side of this assignment,
it must refer to the previous value of volume, assigned in the previous line, as
illustrated below.
second step first step
s d s d
volume ← volume × π
↑ ↑
next value previous value
¯
(4.186) ¯
(1.3)
14 • 1 How to Solve It

With this revision, the algorithm now looks like this:

Algorithm Sphere Volume 2 — Final

Input: the radius r of the sphere


1 volume ← 4 ÷ 3
2 volume ← volume × π
3 repeat the following three times:
4 volume ← volume × r
Output: volume

A trace table for this algorithm looks exactly like the previous one.

Implement from the bottom


We are now prepared to return our attention to the reading level problem. Based
on our decomposition tree in Figure 1.4, there are two ways that we can proceed.
Our first option is to start at the top of the tree and work our way down. For this
to work, we would need to assume that algorithms for the three main subproblems
already exist. Although it is possible to work this way, it is trickier because we
cannot test whether anything is working correctly until we have written algorithms
for everything in the tree.
Instead, we will start at the bottom of the decomposition tree and work our way up,
in what we call a bottom-up implementation. The subproblems that are leaves
of the tree are not dependent on any other subproblems, so we can design algorithms
for these first, make sure they work, and then call upon them in algorithms for
subproblems one level higher. If we continue this process until we reach the root of
the tree, we will have a complete algorithm. Let’s start with an algorithm for the
“Flesch-Kincaid grade level score” subproblem, which takes as inputs the average
number of words per sentence and the average number of syllables per word, and
outputs the grade level of the text according to the Flesch-Kincaid formula.

average words, Flesch-Kincaid


reading level of the text
average syllables grade level score

In pseudocode, we can write this algorithm as follows:

Algorithm Flesch Kincaid

Input: average words, average syllables


1 reading level ← 0.39 × average words + 11.8 × average syllables − 15.59
Output: reading level
1.2 DESIGN AN ALGORITHM • 15

This one-line algorithm simply uses its two input values to compute the grade level,
assigns this value to the variable named reading level, and then outputs this value.
Let’s next write an algorithm to compute the number of syllables in a word. This
algorithm will take a single word as input and output the number of syllables.

number of syllables
word count of syllables
in one word

Reflection 1.9 How do you count the number of syllables in a word? Do you think your
method can be “taught” to a computer?
As you might imagine, a computer cannot use the “clapping method” or something
similar to compute the number of syllables in a word. Instead, a syllable-counting
algorithm will need to ”look at” the letters in the word and follow some rules based
on those letters. Since the number of syllables in a word is defined to be the number
of distinct vowel sounds, a first approximation would be to simply count the number
of vowels in the word.

Algorithm Syllable Count — Draft 1

Input: a word
1 count ← the number of vowels in word
Output: count

Reflection 1.10 What does it mean for an algorithm to be correct? Is this algorithm
correct? If it is not, why not?
An algorithm is correct if it gives the correct output for every possible input. This
algorithm is obviously too simplistic to be correct. For example, the algorithm will
over-count the number of syllables in words containing diphthongs, such as rain and
loan, and in words ending with a silent e.
Reflection 1.11 There is also some ambiguity in this one-line syllable-counting algorithm.
Do you see what it is?
The ambiguity arises from the definition of a vowel in the English language. The
letters a, e, i, o, and u are always vowels but sometimes so is y. So our algorithm
needs to clarify this. Incorporating these insights (and ignoring y as a vowel) leads
to the following enhanced algorithm.
16 • 1 How to Solve It

Algorithm Syllable Count — Draft 2

Input: a word
1 count ← the number of vowels (a, e, i, o, u) in word
2 repeat for each pair of adjacent letters in word:
3 if the letters are both vowels, then subtract 1 from count
4 if word ends in e, then subtract 1 from count
Output: count

Notice two new kinds of pseudocode statements in this algorithm. First, line 2, is a
different kind of loop. Imagine yourself looking carefully for adjacent vowels in a very
long word like consanguineous. You would probably scan along the word visually
or with your finger, from left to right, repeatedly checking pairs of adjacent letters.
This is also what lines 2 and 3 are doing; for each pair of adjacent letters you look at,
check if they are both vowels and subtract one from the count if they are. Another
name for the repetitive process carried out by a loop is iteration; implicit in line 2
is a process of iterating over the letters of the word.
Lines 3 and 4 both illustrate the second new type of statement, called a conditional
statement, or sometimes an if-then statement. Simple conditional statements
like this are self-explanatory: if the condition after the if is true, do the thing after
then. We will work with more sophisticated conditional statements in Chapter 5.
Let’s use a trace table to show the execution of this algorithm on the word “ancient.”

Trace input: word = "ancient"


Step Line count letters Notes
1 1 3 — there are three vowels in "ancient"
2 2 ” "an" first pair of adjacent letters in "ancient" is "an"
3 3 ” ” "an" are not both vowels; no change to count
4 2 ” "nc" next pair of adjacent letters is "nc"
5 3 ” ” "nc" are not both vowels; no change to count
6 2 ” "ci" next pair of adjacent letters is "ci"
7 3 ” ” "ci" are not both vowels; no change to count
8 2 ” "ie" next pair of adjacent letters is "ie"
9 3 2 ” "ie" are both vowels; subtract 1 from count
10 2 ” "en" next pair of adjacent letters is "en"
11 3 ” ” "en" are not both vowels; no change to count
12 2 ” "nt" next pair of adjacent letters is "nt"
13 3 ” ” "nt" are not both vowels; no change to count
14 4 ” ” "ancient" does not end in e; no change to count
Output: count = 2
1.2 DESIGN AN ALGORITHM • 17

The horizontal lines in the trace table make it easier to see the individual iterations
of the loop. In the first step, we count the number of vowels in the input and assign
count to this value. In step 2, we begin the loop by considering the first pair of
adjacent letters in the input, "an". In step 3, we check if these are both vowels. Since
they are not, we leave count alone. In step 4, we repeat the loop by executing line 2
again with the next pair of adjacent letters, "nc". In step 5, we repeat line 3 which,
again, has no effect on the count. In the third iteration, in lines 6–7, the same thing
happens. In the fourth iteration of the loop, starting in step 8, we do find a pair
of adjacent letters that are both vowels, so we subtract one from count. The loop
continues until we run out of letters from the input. Finally, in step 14, we execute
line 4, which finds that the input does not end in e, so count remains 2.
Reflection 1.12 Use trace tables to also execute the algorithm on the words “create” and
“syllable.” Do you get the correct numbers of syllables?
From these examples, you can see that our algorithm is still not correct. Indeed,
designing a computer algorithm that correctly counts syllables for every word in the
English language is virtually impossible; there are just too many exceptions! But we
can certainly get closer than we are now. We will leave it as an exercise for you to
draft further improvements.
To continue our bottom-up implementation of the reading level algorithm, we will
use the Syllable Count algorithm to solve the “total number of syllables” problem.
The idea of the Total Syllable Count algorithm is simple: for each word in the text,
call upon the Syllable Count algorithm for the number of syllables in that word, and
add this number to a running sum of the total number of syllables.

Algorithm Total Syllable Count

Input: a text
1 total count ← 0
2 repeat for each word in the text:
3 number ← Syllable Count (word)
4 total count ← total count + number
Output: total count

In line 1 of the algorithm, we initialize the total count of syllables to zero. Line 2 is
a loop that iterates over all of the words in the text. For every word, we execute
lines 3 and 4, indented to indicate that these comprise the body of the loop. In line
3, we call upon the Syllable Count algorithm to get the number of syllables in the
word that is being considered in that iteration. Syllable Count (word) is shorthand for
“execute the Syllable Count algorithm with input word,” where word is the variable
name representing the word that is being examined in each iteration of the loop.
The output of the Syllable Count algorithm is then assigned to the variable named
number. So altogether, line 3 is shorthand for
18 • 1 How to Solve It

“Execute the Syllable Count algorithm, with input word, and assign the
output to the variable named number.”
Then in line 4, we add the number of syllables in the word to the total count of
syllables.
This is a lot to take in, so let’s once again illustrate with a trace table, using the
first three words of the United Nations charter as input.
Trace input: text = "We the peoples"
Step Line total count word number Notes
1 1 0 — — initialize total count to zero
2 2 ” "We" — do the loop body with word ← "We"
3 3 ” ” 1 get the number of syllables in "We"
4 4 1 ” ” add number to total count
5 2 ” "the" ” do the loop body with word ← "the"
6 3 ” ” 1 get the number of syllables in "the"
7 4 2 ” ” add number to total count
8 2 ” "peoples" ” do the loop body with word ← "peoples"
9 3 ” ” 2 get the number of syllables in "peoples"
10 4 4 ” ” add number to total count
Output: total count = 4

In the trace table, horizontal lines identify the three iterations of the loop, one for
each word in the text. In the first iteration, in step 2, the loop assigns word to be
"We", as the first word in the text. Then, in step 3, number is assigned the output of
Syllable Count ("We"), which means that the Syllable Count algorithm is called upon
to get the number of syllables in "We" and this value (1) is assigned to the variable
number. In step 4, the value of number is added to the total count. Remember that,
in an assignment statement, the righthand side is evaluated first, so the statement
in line 4 is assigning to total count the sum of the previous value of total count and
number, as illustrated below:

total count ← total count + number


↑ ↑ ↑
next value previous value (1)
(1) ( 0)
In the second iteration, starting in step 5, the loop assigns word to be "the", the
Syllable Count algorithm is called upon to get the number of syllables in "the" and this
value is added to total count, bringing its value to 2. Finally, in the third iteration,
starting on line 8, the process repeats with word assigned to be "peoples", bringing
the total number of syllables to 4, which is the output of the algorithm.
To flesh out the entire reading level algorithm, we would continue designing algorithms
for subproblems at the bottom of the tree, and work our way up, calling upon
1.2 DESIGN AN ALGORITHM • 19

algorithms at lower levels from algorithms for levels above. This would continue
until we get to the root of the tree.
Suppose, for the moment, that we have worked our way up the decomposition tree
and that, in addition to the Flesch-Kincaid algorithm, algorithms for the other two
main subproblems have been written—one that computes the average number of
words per sentence and one that computes the average number of syllables per word.
Also suppose that we have named these algorithms Average Words Per Sentence and
Average Syllables Per Word, respectively. Then the final reading level algorithm would
look like the following.

Algorithm Reading Level

Input: a text
1 average words ← Average Words Per Sentence (text)
2 average syllables ← Average Syllables Per Word (text)
3 reading level ← Flesch-Kincaid (average words, average syllables)
Output: reading level

Line 1 of the algorithm is shorthand for


“Execute the Average Words Per Sentence algorithm, with input text, and
assign the output to the variable named average words.”
Similarly, line 2 of the algorithm is shorthand for
“Execute the Average Syllables Per Word algorithm, with input text, and
assign the output to the variable named average syllables.”
Finally, line 3 calls upon the Flesch-Kincaid algorithm, with the values of these two
variables as input, to compute the Flesch-Kincaid grade level score. The output of
this algorithm is then assigned to the variable named reading level, which is output
by the algorithm.
We invite you to take a stab at writing the remaining algorithms in the exercises.

Exercises
1.2.1. Decompose each of the following problems into subproblems. Continue the
decomposition until you think each subproblem is sufficiently simple to solve.
Explain your rationale for stopping the decomposition where you did.
(a)* an exercise routine from warmup to cool down
(b) your complete laundry routine
(c) writing a paper for a class
(d) your morning routine
(e) planning a multiple course menu
20 • 1 How to Solve It

1.2.2. Suppose you want to find the area of each of the following shaded regions. In
each of the diagrams, one square represents one square unit. Decompose each
problem into subproblems that make finding the solution easier. (You do not
need to actually find the areas.)

(a)* (b) (c)

1.2.3. Look up the organizational chart for your school. Choose one division and
explain how the organization of that division supplies a functional abstraction
to the office that oversees the division.
1.2.4* Use a trace table to show how the final Sphere Volume 2 algorithm executes with
input r = 7.
1.2.5. Use a trace table to show how the second draft of the Syllable Count algorithm
executes on the word algorithm. Is the result correct?
1.2.6. The following algorithm computes the surface area of a box.

Algorithm Surface area of a box

Input: length, width, height


1 area 1 ← length × width
2 area 2 ← length × height
3 area 3 ← width × height
4 surface ← area 1 + area 2 + area 3
5 surface ← surface × 2
Output: surface

Use a trace table (started below) to show how the algorithm executes with
inputs length = 4, width = 5, and height = 2.
Trace input: length = 4, width = 5, height = 2
Step Line area 1 area 2 area 3 surface Notes
1 1 20 — — — area 1 ← length × width
2 2

Output:

1.2.7* The following algorithm determines the winner of an election between two
candidates, Laura and John. The input is a list votes like [Laura, Laura, John,
Laura, . . . ].
1.2 DESIGN AN ALGORITHM • 21

Algorithm Count votes

Input: votes
1 laura ← 0
2 john ← 0
3 repeat once for each entry in votes:
4 if the entry is for Laura, then add 1 to laura
5 otherwise, add 1 to john
6 if laura > john, then winner ← Laura
7 otherwise, winner ← John
Output: winner

Use a trace table (started below) to show how the algorithm executes with input
votes = [John, Laura, Laura, John, Laura].
Trace input: votes = [John, Laura, Laura, John, Laura]
Step Line laura john winner Notes
1 1 0 — — laura set to 0
2 2

Output:

1.2.8. There is a subtle mistake in the algorithm in Exercise 1.2.7. Describe and fix it.
1.2.9* Revise the original Sphere Volume algorithm on page 10 so that it also uses a
variable instead of referring to the “previous result.”
1.2.10. Write yet another algorithm for finding the volume of a sphere.
1.2.11. Write an algorithm to sort a stack of any 5 cards by value in ascending order. In
each step, your algorithm may compare or swap the positions of any two cards.
1.2.12. Write an algorithm to walk between two nearby locations, assuming the only
legal instructions are “Take s steps forward,” and “Turn d degrees to the left,”
where s and d are positive integers.
1.2.13. The term algorithm was derived from the name of Muh.ammad ibn Mus¯ ¯ a al­
Khwārizmj̄ (c. 780–c. 850), a Persian mathematician who introduced both Arabic
numerals and algebra to the world. The term algebra is derived from the Latin
translation of the title of his book, “The Compendious Book on Calculation
by Completion and Balancing” [4], which introduced algebra. The following
algorithm for a common algebraic operation is from an English translation of
this work.

You know that all mercantile transactions of people, such as buying and selling,
exchange and hire, comprehend always two notions and four numbers, which are
stated by the enquirer; namely, measure and price, and quantity and sum. The
number which expresses the measure is inversely proportionate to the number
22 • 1 How to Solve It

which expresses the sum, and the number of the price inversely proportionate
to that of the quantity. Three of these four numbers are always known, one
is unknown, and this is implied when the person inquiring says “how much?”
and it is the object of the question. The computation in such instances is this,
that you try the three given numbers; two of them must necessarily be inversely
proportionate the one to the other. Then you multiply these two proportionate
numbers by each other, and you divide the product by the third given number, the
proportionate of which is unknown. The quotient of this division is the unknown
number, which the inquirer asked for; and it is inversely proportionate to the
divisor.
Examples.—For the first case: If you are told “ten for six, how much for four?”
then ten is the measure; six is the price; the expression how much implies the
unknown number of the quantity; and four is the number of the sum. The number
of the measure, which is ten, is inversely proportionate to the number of the
sum, namely, four. Multiply, therefore, ten by four, that is to say, the two known
proportionate numbers by each other; the product is forty. Divide this by the
other known number, which is that of the price, namely, six. The quotient is six
and two-thirds; it is the unknown number, implied in the words of the question
“how much?” it is the quantity, and inversely proportionate to the six, which is
the price.

There are four variables identified in the passage: measure, price, sum, and
quantity. Write an algorithm in pseudocode that answers the “how much?”
question posed in the example when the first three quantities are given as input.
1.2.14* Using the Syllable Count algorithm as a guide, write an algorithm named Word
Count that approximates the total number of words in a text. Your algorithm
should take a text as input and output a count of words. Like the Syllable Count
algorithm, use a loop to look at each letter in the text and adjust a count as
appropriate. As with counting syllables, this problem is fraught with complexity
arising from the English language, so your algorithm need not be perfect.
1.2.15. Write an algorithm named Sentence Count to count the total number of sentences
in a text. Your algorithm should take a text as input and output a count of
sentences. The guidance from the previous exercise also applies.
1.2.16* Using Figure 1.4 and the Reading Level algorithm on page 19 as guides, design the
Average Words Per Sentence algorithm. Call upon your Word Count and Sentence
Count algorithms to do most of the work.
1.2.17. Using Figure 1.4 and the Reading Level algorithm on page 19 as guides, design
the Average Syllables Per Word algorithm. Call upon your Word Count algorithm
and the Total Syllable Count algorithm to do most of the work.
1.2.18. Enhance the Syllable Count (Version 2) algorithm on page 16 so that it correctly
counts the number of syllables in
(a) plural words
(b) words ending in a consonant plus le (e.g., syllable)
(c) words containing a y that acts like a vowel
(d) the word algorithm
1.3 WRITE A PROGRAM • 23

1.3 WRITE A PROGRAM

Third, carry out your plan, checking each step.

The next step in the problem solving process is to “carry out your plan” by translat­
ing your algorithm into a program that a computer can execute. A program must
adhere to a set of grammatical rules, called syntax , that are defined by a particular
programming language. In this book, we will use a programming language called
Python. You will find that programming in Python is not too different from writing
algorithms in pseudocode, which is why it is a great first language. But Python
is not a toy language either; it has become one of the most widely used program­
ming languages in the world, especially in data science, bioinformatics, and digital
humanities.
Writing programs (or “programming”) is a hands-on activity that allows us to test
our algorithms, apply them to real inputs, and harness their results, in tangible and
satisfying ways. Learning how to program empowers us to put our algorithms into
production. Solving problems and writing programs should also be fun and creative.
Guido van Rossum, the inventor of Python understood this when he named Python
after the British comedy series “Monty Python’s Flying Circus!”
In this section, we will not be able to fully realize our reading level algorithm as a
program just yet. Some of the steps that are easy to write as pseudocode, such as
breaking a text into individual words, are actually more involved than they look on
paper. But we will be able to implement the Flesch-Kincaid algorithm at the bottom
of our decomposition tree, and get oriented for what awaits in future chapters. Before
long, you will be able to implement everything from the previous section and much
more!

Welcome to the circus


As you work through this book, we highly recommend that you do so in front of a
computer. The only way to learn how to program is to do it, so every example we
provide is meant to be tried by you. Then go beyond the examples, and experiment
with your own ideas. Instead of just wondering, “What would happen if I did this?”,
type it in and see! To get started, launch the application called IDLE that comes
with every Python distribution (or another programming environment recommended
by your instructor). You should see a window appear with something like this at the
top:
Python 3.8.4 (v3.8.4:dfa645a65e, Jul 13 2020, 10:45:06)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>>
The program executing in this window is known as a Python shell . The first line
tells you which version of Python you are using (in this case, 3.8.4). The programs
in this book are based on Python version 3.6 and higher. If you need to install a
Other documents randomly have
different content
Mr. Liebeler. Now you say that you had the idea that the shots
may have come from up in that area?
Mr. Smith. Yes, sir; that is just what, well, like I say, the sound of
it. That was the most helpless and hopeless feeling I ever had.
Mr. Liebeler. Well, you mentioned before there was an echo from
the shots in the area.
Mr. Smith. Yes, sir.
Mr. Liebeler. Probably caused by the fact that there are some
large buildings around the area where the shots were fired from?
Mr. Smith. Yes.
Mr. Liebeler. Now did you at any time have occasion to look up to
the railroad tracks that went across the triple underpass?
Mr. Smith. Yes, sir; I looked up there after I was going up to
check there.
Mr. Liebeler. You didn't have any occasion to look up there before
you heard the shots?
Mr. Smith. No, sir.
Mr. Liebeler. After you heard the shots, you proceeded down
along the bushes here between the street that runs in front of the
Texas School Book Depository Building and Elm Street to
approximately point 5, and then when you went down looking to the
cars, you then had occasion to look up at the railroad tracks running
over the triple underpass?
Mr. Smith. Yes, sir.
Mr. Liebeler. Did you see anybody up there?
Mr. Smith. Yes, sir; there was two other officers there, I know.
Mr. Liebeler. Were there any other people up there, that you can
remember?
Mr. Smith. No, sir; none that I remember.
Mr. Liebeler. But you remember that there were two police
officers up there?
Mr. Smith. Yes, sir.
Mr. Liebeler. Now you searched these cars in this parking lot area
down there by the railroad tracks on from point 5 down toward the
main railroad tracks that cross over the triple underpass. Did you
find anything that you could associate in any way with the
assassination?
Mr. Smith. No, sir.
Mr. Liebeler. How long did you remain down in that area?
Mr. Smith. Oh, I would say approximately 15 to 20 minutes.
Mr. Liebeler. During that time, you continued searching through
automobiles and searching the general area in the parking lot back
there; is that right?
Mr. Smith. Yes, sir.
Mr. Liebeler. What did you do after you had searched this area?
Mr. Smith. Well, it was, I don't remember whether this was a
deputy sheriff—I don't know his name—he was in civilian clothes—
he said they came from the building up here. And by that time, of
course, all the police around there sealed the building off, and I
went to the front door here on the, well, you might say, the Houston
Street side. I and Barnett, and we sealed the front door and didn't
let anyone in or out until he was passed by the chief.
Mr. Liebeler. Let me ask you this. Before you went up to the
School Book Depository Building, am I correct in understanding that
you did thoroughly search the area of the parking lot, you and the
other officers?
Mr. Smith. Well, now, I didn't go into all the cars. I looked into
them, and I was well satisfied in my mind that he wasn't around
there.
Some of the cars were locked, and I just looked into all of them
around there, and I went back to the building.
Mr. Liebeler. Who gave you instructions to go to the front door of
that building, do you remember?
Mr. Smith. I believe it was Sergeant Howard.
Mr. Liebeler. Sergeant Howard?
Mr. Smith. Sergeant Howard, or Sergeant Harkness.
Mr. Liebeler. So to the best of your recollection, it was one of
those two men?
Mr. Smith. Yes, sir. Wait—let's strike that. No; it wasn't. It was
Chief Lumpkin give us the direct order, I and Barnett, not to let
anyone in or out of that building; that's right—Deputy Chief
Lumpkin.
Mr. Liebeler. Where did you see him in order to receive that
order?
Mr. Smith. I started back up here to the building, and we were
just about at the front door when he contacted me and Barnett then.
Mr. Liebeler. He instructed you and Barnett to stand at the front
door and not let anyone in or out?
Mr. Smith. Right.
Mr. Liebeler. Do you know approximately what time that was?
Mr. Smith. No, sir; it must have been about 1. It was after 1
o'clock. I don't remember; no.
Mr. Liebeler. How long did you and Barnett remain there at the
front door?
Mr. Smith. Until about 2:30; I think I got off there.
Mr. Liebeler. Did you at any time go into the building?
Mr. Smith. No, sir.
Mr. Liebeler. Do you know whether other men were assigned to
watch the back door?
Mr. Smith. No, sir; I don't know. I am quite certain there was.
Mr. Liebeler. But you had no personal knowledge of it at the
time?
Mr. Smith. No, sir.
Mr. Liebeler. Because you were assigned to the front door, and
that is where you stayed?
Mr. Smith. Yes, sir.
Mr. Liebeler. In fact, did you let anybody in or out of the building?
Mr. Smith. Well, now, we let police officers in, of course, and
firemen.
Mr. Liebeler. The firemen came into the building?
Mr. Smith. Yes, sir; there was something on that that they had to
get some—what was that, I don't recall what it was that they come
in there for now.
Mr. Liebeler. There were some firemen from the Dallas Fire
Department that went into the building?
Mr. Smith. Yes, sir.
Mr. Liebeler. Did they come back to the front door?
Mr. Smith. Yes, sir.
Mr. Liebeler. How about Secret Service; were there any Secret
Service agents around?
Mr. Smith. I don't know, sir.
Mr. Liebeler. Do you know Agent Sorrels, the agent in charge of
the Dallas office of the Secret Service?
Mr. Smith. I saw him a few minutes, but I don't know him
personally.
Mr. Liebeler. Do you remember seeing him around that day?
Mr. Smith. No, sir; I don't remember.
Mr. Liebeler. Did you at any time see Lee Harvey Oswald come in
or out of the building, or in the area at all?
Mr. Smith. No, sir.
Mr. Liebeler. Is there anything that happened while you were
standing there with Barnett at the front door that you think would be
of significance that the Commission should know about that I
haven't asked you about?
Mr. Smith. No, sir; I don't.
Mr. Liebeler. You just maintained the general guard duty there
and only let the police officers and fire department in, and you don't
have any specific recollection as to Secret Service agents. How about
FBI agents; were there some of those?
Mr. Smith. Yes, sir; there were FBI agents.
Mr. Liebeler. You let them go in?
Mr. Smith. Yes, sir.
Mr. Liebeler. Do you remember any specific FBI agents that were
there?
Mr. Smith. No, sir; I don't remember any of the names.
Mr. Liebeler. Who finally relieved you from that particular duty
post?
Mr. Smith. Let me think here a minute now. Chief Lumpkin, I
know—I don't recall who the officer was.
Mr. Liebeler. I don't think it is of any particular importance if you
can't recall. What did you do after you were finally relieved?
Mr. Smith. I don't know if this is of significance either, but they
had set up, the Salvation Army had some coffee and I had a cup of
coffee and proceeded on back to the Mercantile Bank. I had an extra
job there that evening.
Mr. Liebeler. You were relieved from your duty post?
Mr. Smith. Yes, sir.
Mr. Liebeler. And went on about your own personal affairs?
Mr. Smith. Yes, sir.
Mr. Liebeler. Did you conduct any additional investigation or have
anything to do with the investigation of the assassination after that?
Mr. Smith. No, sir.
Mr. Liebeler. Did you know Officer Tippit?
Mr. Smith. Remotely. I didn't know him real well. Just knew him
when I saw him.
Mr. Liebeler. When did you first hear about Oswald's capture?
Mr. Smith. It was after I left my post.
Mr. Liebeler. After you left your post?
Mr. Smith. Yes; in fact, just before I got off from working at the
bank. Just before 6 o'clock. A squad of detectives, I don't recall their
names, but they told me they got a man over at the Texas Theatre
that they thought might have been the one.
Mr. Liebeler. After you heard the shots and went from Point 4 on
Commission Exhibit No. 354 down to point 5 searching the bushy
area here, did you have any occasion to look up in the windows of
any of the buildings surrounding the intersection of Elm and Houston
Streets?
Mr. Smith. No, sir; I was—pardon the expression—beating the
bushes and checking the cars.
Mr. Liebeler. So you never saw anything in any of those windows
at all?
Mr. Smith. No, sir.
Mr. Liebeler. Are you familiar with the traffic patterns on these
three streets here, Commerce, Main, and Elm Streets, as they go
down under the triple underpass?
Mr. Smith. Yes, sir.
Mr. Liebeler. The motorcade came down Main Street from the
east to the intersection of Main Street and Houston, did it not?
Mr. Smith. Yes; headed west on Main.
Mr. Liebeler. Yes; and it turned right on Houston Street and then
turned left on Elm and was headed toward the triple underpass
when the assassination occurred. What would have prevented the
motorcade from going directly down Main Street under the triple
underpass, remembering now that the motorcade wanted to go onto
Stemmons Freeway?
Mr. Smith. I don't know, sir.
Mr. Liebeler. Now, could you have gone straight down Main Street
and gotten onto Stemmons Freeway down here?
Mr. Smith. Yes, sir.
Mr. Liebeler. Where the three streets go under the triple
overpass, there is a concrete barrier between Elm Street and Main
Street; is there not?
Mr. Smith. What do you mean?
Mr. Liebeler. Where the streets actually go under the railroad
tracks here.
Mr. Smith. Yes, sir.
Mr. Liebeler. Now where is the entrance as we go off, as we see
the three streets going off the picture here, Commission Exhibit No.
354? Where is the entrance to the Stemmons Freeway?
Mr. Smith. It is back off.
Mr. Liebeler. It is not shown on the picture?
Mr. Smith. No, sir; it is back off here.
Mr. Liebeler. To go down Stemmons Expressway or Freeway
towards the trade mart, you would have to turn how? Would you
turn to your right?
Mr. Smith. Yes, sir.
Mr. Liebeler. Now could you have actually gone off to the right
and crossed over Elm Street if you had been on Main Street and
gone under the triple underpass?
Mr. Smith. They merge.
Mr. Liebeler. They all merge together down there?
Mr. Smith. Yes, sir.
Mr. Liebeler. So as far as you know, there was no reason why the
motorcade couldn't have gone straight down Elm Street and gone on
to the Stemmons Freeway headed for the trade mart?
Mr. Smith. As far as I know, there is no reason.
Mr. Liebeler. Is it possible that as you come down Main Street, if
you stayed directly on Main Street going under the triple underpass,
that you might have difficulty in making the turn with a big car from
Main Street to go onto Stemmons Freeway?
Mr. Smith. Yes, sir.
Mr. Liebeler. I don't think I have any more questions about the
situation, unless you can think of something else that you might
have seen or observed that day that I haven't asked you about that
you think the Commission should know.
Mr. Smith. Sir, I just can't think of anything else.
Mr. Liebeler. I want to thank you very much for coming over. I
appreciate your cooperation.
Mr. Smith. Yes, sir; thank you.
TESTIMONY OF WELCOME EUGENE
BARNETT
The testimony of Welcome Eugene Barnett was taken at 3:50
p.m., on July 23, 1964, in the office of the U.S. attorney, 301 Post
Office Building, Bryan and Ervay Streets, Dallas, Tex., by Mr. Wesley
J. Liebeler, assistant counsel of the President's Commission.

Mr. Liebeler. Before you sit down, will you raise your right hand?
Do you solemnly swear that the testimony you are about to give will
be the truth, the whole truth, and nothing but the truth, so help you
God?
Mr. Barnett. I do.
Mr. Liebeler. Please sit down. My name is Wesley J. Liebeler. I am
an attorney for the President's Commission investigating the
assassination of President Kennedy. I have been authorized to take
your testimony by the Commission, pursuant to authority granted to
it by Executive Order 11130 dated November 29, 1963, and joint
resolution of Congress No. 137. Pursuant to the rules of the
Commission governing the taking of testimony, you are entitled to
have an attorney present if you want one, and you are entitled to 3
days' notice of the hearing. I know you did not get the 3 days' notice
because of schedule difficulties that we had, and you were just
advised of it this morning, I believe. I assume, however, that since
you are here, that you are prepared to go ahead with your testimony
without having an attorney.
Mr. Barnett. Yes.
Mr. Liebeler. Would you state your full name for the record?
Mr. Barnett. Welcome Eugene Barnett.
Mr. Liebeler. When and where were you born?
Mr. Barnett. July 12, 1932, New Hope, Tex.
Mr. Liebeler. You are apparently a uniformed officer of the Dallas
Police Department, isn't that right?
Mr. Barnett. Yes, sir.
Mr. Liebeler. How long have you been in the Dallas police?
Mr. Barnett. Eight and a half years.
Mr. Liebeler. It is my understanding that you were assigned to
the area of Elm and Houston Streets on November 22, 1963; is that
correct?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Would you tell us how you received instructions to
go there, when you received them, what you were told, and what
happened? Would you tell us what happened on that day, in other
words?
Mr. Barnett. We made detail around 9 o'clock. We were
instructed to be at our assignments at 10. We were given our
assignments, each one was given an assignment, and I was told to
watch the crowd, watch for people throwing stuff from the crowd at
the President's party, to keep the traffic clear, and to stop the traffic
when the President came by. Then when the President came by, I
heard three shots.
Mr. Liebeler. Now, going back, you got to the area around 10
o'clock; is that right?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Where did you go when you got there?
Mr. Barnett. Well, there were three of us assigned to that one
corner.
Mr. Liebeler. Who were the other officers?
Mr. Barnett. Who were the other officers?
Mr. Liebeler. Yes.
Mr. Barnett. J. D. Smith, and another officer named Smith. I
don't know his initials. E. L., I believe.
Mr. Liebeler. Did you divide your duties among yourselves when
you got there, or had you been specifically instructed as to what
each one was supposed to do?
Mr. Barnett. We divided our duties.
Mr. Liebeler. How did you do that?
Mr. Barnett. Well, as best I remember, we each picked a corner
and got on the corner. We were advised to stay on our corner, not to
cross over to idly talk, but to stay on the corner and keep our eyes
open and be ready.
Mr. Liebeler. Which corner did you station yourself at? I have a
picture here of an aerial view—you can sit down—Commission
Exhibit No. 354.
Of course, you can recognize the intersection of Elm and
Houston here in the left-hand upper portion of the picture; can you
not?
Mr. Barnett. I was right here.
Mr. Liebeler. At No. 1?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Did you remain there at all times from 10 o'clock
until the motorcade arrived?
Mr. Barnett. Yes; well, of course, I was here until we got word to
stop the traffic, and I stepped out of this position here. I had to stop
traffic from Houston here and help the other officers stop it on Elm,
and stop this traffic on this small street that goes in front of the
Depository Building.
Mr. Liebeler. When the motorcade actually came, you moved over
pretty much into Houston Street?
Mr. Barnett. Yes, sir.
Mr. Liebeler. To stop the traffic that was coming?
Mr. Barnett. South on Houston Street.
Mr. Liebeler. South on Houston Street?
Mr. Barnett. Yes, sir; Elm Street is so wide, and I helped these
officers here stop this traffic here.
Mr. Liebeler. We have written the No. 4 on here before and it is
kind of hard to read. You also helped to stop the traffic that was
coming down here in the area of No. 4, which would have been the
traffic on Elm Street?
Mr. Barnett. Yes, sir; I was standing right about this position right
here.
Mr. Liebeler. Right about No. 8?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Now specifically, were you given any instructions
when you left that morning when you made detail, to observe and
scan the windows of the buildings around that area?
Mr. Barnett. No, sir; we weren't, but that is just one thing you
always do. It is understood that you have the buildings to watch.
Mr. Liebeler. But there were no specific instructions given to any
of the officers, so far as you know, when they left that morning,
about watching the windows in the area?
Mr. Barnett. I don't see any use in being instructed on that.
Mr. Liebeler. Well, regardless of that fact——
Mr. Barnett. There was no instructions; no.
Mr. Liebeler. Now from where you were standing at position 1
prior to the motorcade's arrival, you were in a position to view the
windows on the entire south side of the Texas School Book
Depository Building; were you not?
Mr. Barnett. Yes.
Mr. Liebeler. Did you look up at those windows?
Mr. Barnett. Yes.
Mr. Liebeler. How many times did you look up at those windows
before the motorcade came? Can you tell us with what frequency?
Mr. Barnett. I looked up twice. Maybe once at 11, probably a few
minutes after 11—probably a few minutes after 11. It was raining
part of the morning, and when I found out that the people in the
building were going to come outside and watch the President, I
looked up at the building, and then I looked at all the buildings, and
there were no windows that I noticed open then. But after a few
minutes before the President came by, I didn't look any more. I
started watching the crowd.
Mr. Liebeler. So just before the motorcade approached, you
moved over and also stopped the automobile traffic and were
observing the crowd, so you did not look at the windows on or about
the time the motorcade came?
Mr. Barnett. I couldn't. I was too busy. [Referring to picture.] I
got this in the wrong place. It needs to be about this position right
here, instead of here. I was right here. I got it too far, but I could
see the President's car from the position I was, so I had to be right
here [pointing].
Mr. Liebeler. You are satisfied you were further out into the
intersection?
Mr. Barnett. Right there [indicating].
Mr. Liebeler. [Marking]. In the general vicinity of No. 9?
Mr. Barnett. Yes, sir; the car passed within a few feet of me, and
I was holding some people, or seeing that they stayed back, and one
small boy started. I was afraid he was going to get too close and I
stopped him.
Mr. Liebeler. Now the motorcade made the turn onto Elm Street
from Houston Street, and you were standing at approximately in
position No. 9, and you indicated before that you heard the shots
fired: is that right?
Mr. Barnett. Yes, sir.
Mr. Liebeler. How many shots did you hear?
Mr. Barnett. Three.
Mr. Liebeler. Was there any echo in the area from where you
were standing?
Mr. Barnett. What do you mean by echo? You mean another
sound besides the shots?
Mr. Liebeler. Yes.
Mr. Barnett. No; I didn't hear any echo. The whole sound
echoed. The sound lingered, but as far as just two definite distinct
sounds, when each shot was fired, that one sound would linger in
the air, but there would be nothing else until the next shot.
Mr. Liebeler. Did you see any of the shots hit the President?
Mr. Barnett. Well, when the first shot—I was looking at the
President when the first shot was fired, and I thought I saw him
slump down, but I am not sure, and I didn't look any more then. I
thought he was ducking then.
Mr. Liebeler. Now when you were standing up there in position
No. 9, you were in a spot where you could look right down Elm
Street and see the railroad tracks down here which pass over the
triple underpass?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Did you see anybody on the railroad tracks?
Mr. Barnett. One or two officers. Two officers, I believe.
Mr. Liebeler. Was there anybody else, as far as you can recall?
Mr. Barnett. That is all I saw.
Mr. Liebeler. Did you have an opinion when you heard the shots
as to where they came from?
Mr. Barnett. Yes, sir.
Mr. Liebeler. What did you think about them?
Mr. Barnett. When the first shot was fired, I thought it was a
firecracker, and I looked across the street. In fact, I scanned the
whole area to see where people would jump or move or make some
action.
Mr. Liebeler. You couldn't tell specifically where it had come from?
Mr. Barnett. Not the first one, but I thought it was a firecracker.
But none of the people moved or took any action, whereas they
would have if a firecracker went off. And when the second shot was
fired, it sounded high. The sound of the second one seemed to me
like it was coming from up high, and I looked up at the building and
I saw nothing in the windows. In fact, I couldn't even see any
windows at that time.
Mr. Liebeler. In the Texas School Book Depository?
Mr. Barnett. No, sir; because I was standing too close, was the
reason. And I looked back again at the crowd, and the third shot
was fired. And I looked up again, and I decided it had to be on top
of that building. To me, it is the only place the sound could be
coming from.
Mr. Liebeler. What did you do when you concluded that the shots
were coming from that building?
Mr. Barnett. I ran to the back of the building.
Mr. Liebeler. Ran down Houston Street?
Mr. Barnett. Yes, sir.
Mr. Liebeler. There is a door in the back of the Texas School Book
Depository. Does it face on Houston or around the corner?
Mr. Barnett. It is around the corner from Houston Street.
Mr. Liebeler. Did you go in the building?
Mr. Barnett. No, sir; I didn't get close to it, because I was
watching for a fire escape. If the man was on top, he would have to
come down, and I was looking for a fire escape, and I didn't pay
much attention to the door.
I was still watching the top of the building, and so far as I could
see, the fire escape on the east side was the only escape down.
Mr. Liebeler. Since you surmised that the shots had come from
the building, you looked up and you didn't see any windows open.
You thought they had been fired from the top of the building?
Mr. Barnett. That's right.
Mr. Liebeler. So you ran around here on Houston Street
immediately to the east of the Texas School Book Depository
Building and watched the fire escape?
Mr. Barnett. I went 20 foot past the building still on Houston,
looking up. I could see the whole back of the building and also the
east side of the building.
Mr. Liebeler. Did you see anybody coming off the fire escape up
there, or any movement on top of the building?
Mr. Barnett. Not a thing.
Mr. Liebeler. What did you do after you went around behind the
building?
Mr. Barnett. I looked behind the building and I saw officers
searching the railroad cars. I looked around in front towards the
front of the building and I saw officers going west.
Mr. Liebeler. Going west down that little street there in front of
the School Book Depository Building?
Mr. Barnett. Yes; but there was no sign they were going into the
building or watching the building, so I decided I was the only one
watching the building. So since this was the only fire escape and
there was officers down here watching this back door, I returned
back around to the front to watch the front of the building and the
fire escape. Then I decided maybe I had been wrong, so I saw the
officers down here searching.
Mr. Liebeler. You mean the officers went on down toward No. 5
on our Exhibit No. 354?
Mr. Barnett. When I got to the front, some of the officers were
coming back toward me, started back toward me.
Mr. Liebeler. You were still back near the intersection of Elm and
Houston?
Mr. Barnett. Yes, sir; I was back where No. 8 is then. That was
probably 2½ minutes after the last shot was fired. About that time,
my sergeant came up from this way, from the north of Houston
Street and asked me to get the name of that building. I broke and
ran to the front and got the name of it. There were people going in
and out at that time. I ran back and told him the name of it, and
about that time a construction worker ran from this southwest
corner of the intersection up to me and said, "I was standing over
there and saw the man in the window with the rifle." He and I and
the sergeant all three broke and ran for the door. I kept the man
there with me. The sergeant ran to the back to make sure it was
covered. I kept the man there until they took him across the street
to the courthouse. I was there until 3 o'clock, at the door there with
one of the other officers, J. D. Smith.
Mr. Liebeler. You didn't actually go into the building at the time?
Mr. Barnett. No.
Mr. Liebeler. How long do you think it was from the time the last
shot was fired until the time you were at the front door keeping
people from going in and out?
Mr. Barnett. It was around 2½ minutes. Maybe between 2½ or 3
minutes.
Mr. Liebeler. From the time the last shot was fired until the time
you were standing at that front door?
Mr. Barnett. Yes.
Mr. Liebeler. Did you let anybody out of the building after you got
there?
Mr. Barnett. No, sir; until they were authorized.
Mr. Liebeler. Who was in a position to authorize people to come
in and out?
Mr. Barnett. Well, of course, for sometime no one left except city,
county, and Federal officers, and then after the people in the
building were took into the small room there and questioned, they
were brought to the door by a lieutenant, which I don't remember
his name, but that was sometime after, and he brought them to the
door and told us to let them out.
Mr. Liebeler. Now, it was possible that people could have left the
building between the time the last shot was fired and the time you
and Officer Smith stationed yourselves there?
Mr. Barnett. When I went to the door to get the name of the
building, there were people going in and out then.
Mr. Liebeler. There were?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Do you think it was as quickly as 2½ minutes from
the time the last shot was fired until the time you got to the front
door? Do you think it was that quick?
Mr. Barnett. I believe it was 2½ minutes probably from the time I
ran from the back to the front. That was probably 2½ minutes. Then
it took me 20 or 30 more seconds before I got to the front there.
Mr. Liebeler. So your recollection is that it was fairly short order
that you got to the front door?
Mr. Barnett. Three minutes at the most.
Mr. Liebeler. Now who was the one sergeant who instructed you
to post yourself there at the door, or was it somebody else?
Mr. Barnett. Sergeant Howard.
Mr. Liebeler. You remained there at the door for how long?
Mr. Barnett. Until 3 o'clock. Close to 11:30 to 3—close to 12:30
to 3.
Mr. Liebeler. At which time you were relieved from duty?
Mr. Barnett. Yes, sir; from that position I had to go back to my
regular assignment at Commerce and Akard.
Mr. Liebeler. Did you notice Oswald around that area at anytime?
Mr. Barnett. No, sir.
Mr. Liebeler. Later on you saw his picture in the paper and, of
course, on television?
Mr. Barnett. Yes, sir.
Mr. Liebeler. You had no recollection of seeing him in the area at
all?
Mr. Barnett. None whatsoever. There were hundreds of people in
that intersection.
Mr. Liebeler. Have you ever talked to any other officer in the
department that remembers seeing him in the area at all?
Mr. Barnett. No; I haven't.
Mr. Liebeler. Have you heard of anybody that saw him there at
the time?
Mr. Barnett. Well, of course, I heard other officers that went up
in the building and talked to him.
Mr. Liebeler. Officer Baker was one?
Mr. Barnett. I haven't talked to the officer.
Mr. Liebeler. So you were pretty sure fairly quickly that the shots
had come from the Texas School Book Depository?
Mr. Barnett. Yes, sir.
Mr. Liebeler. There was no notion in your mind that they could
have come from these railroad tracks down here around the triple
underpass?
Mr. Barnett. To me, it is impossible.
Mr. Liebeler. From the sound of the shots?
Mr. Barnett. The sounds were high, and if it was down here, it
wouldn't echo. It would be a low sound. For a shot to echo, it has to
be high up.
Mr. Liebeler. You mean to hang?
Mr. Barnett. To hang like that.
Mr. Liebeler. Now there were altogether three policemen assigned
to the corner of Elm and Houston; is that right?
Mr. Barnett. Yes, sir.
Mr. Liebeler. Were there any other men assigned down the length
of Elm Street here, that you know?
Mr. Barnett. Not that I know of. There were no men stationed
permanently there.
Mr. Liebeler. The responsibility of control in that area would have
been the job of the motorcycle riders and the Secret Service men?
Mr. Barnett. That's right.
Mr. Liebeler. Are there any general orders that are issued to
police officers in regard to the scanning of windows when
motorcades go by and that sort of thing?
Mr. Barnett. Well, in our training, we are told to scan windows,
among lots of things. Look on top of buildings, windows, cars, but,
of course, these things you are taught from the beginning. You don't
have to be reminded of it every day. That is what you are taught to
do, and it would take too long to remind us of everything they are
supposed to do.
Mr. Liebeler. Every time you went out on an assignment?
Mr. Barnett. Yes, sir; it would be impossible. That is why you are
trained for a job.
Mr. Liebeler. Can you think of anything else that you saw or
heard on that day that you haven't told us about now, that you think
we would be interested in?
Mr. Barnett. No, sir; I believe that is all.
Mr. Liebeler. Thank you very much, officer, for coming in. We
appreciate your cooperation.
Mr. Barnett. You are welcome.
TESTIMONY OF EDDY RAYMOND
WALTHERS
The testimony of Eddy Raymond Walthers was taken at 8:16
p.m., on July 23, 1964, in the office of the U.S. attorney, 361 Post
Office Building, Bryan and Ervay Streets, Dallas, Tex., by Mr. Wesley
J. Liebeler, assistant counsel of the President's Commission.

Mr. Liebeler. My name is Wesley J. Liebeler, [spelling] L-i-e-b-e-l-


e-r, and I am an attorney on the staff of the President's Commission
investigating the assassination of President Kennedy. I have been
authorized to take your testimony by the Commission pursuant to
authority granted to it by Executive Order 11130, dated November
29, 1963, and joint resolution of Congress 137. Pursuant to the rules
of the Commission covering the taking of testimony, you are entitled
to have an attorney present and you are entitled to 3 days' notice of
your hearing. I know you didn't get the 3 days' notice of your
hearing, but that can be waived by the witness and I assume that
since you are here you are prepared to proceed and that we may
proceed without your attorney being present?
Mr. Walthers. Yes.
Mr. Liebeler. Will you stand and take the oath, please? Do you
solemnly swear that the testimony you are about to give will be the
truth, the whole truth, and nothing but the truth, so help you God?
Mr. Walthers. I do.
Mr. Liebeler. Will you state your name, please?
Mr. Walthers. Eddy Raymond Walthers.
Mr. Liebeler. When and where were you born?
Mr. Walthers. I was born here in Dallas County in 1928 on July
17.
Mr. Liebeler. Where do you live?
Mr. Walthers. I live at 2527 Boyd Street in Dallas.
Mr. Liebeler. Are you presently a deputy sheriff in Dallas County,
Tex.?
Mr. Walthers. Yes.
Mr. Liebeler. How long have you been a deputy sheriff?
Mr. Walthers. About 9 years.
Mr. Liebeler. I understand that you were in or about the area of
the Texas School Book Depository Building on November 22, 1963; is
that correct?
Mr. Walthers. Yes, sir.
Mr. Liebeler. How did you come to be there at that time?
Mr. Walthers. I was standing in front of the sheriff's office on
Main Street and close to Houston with Mrs. Decker watching the
parade.
Mr. Liebeler. Now, there is a building right there at the corner of
Elm Street and Houston Street, what has been referred to as the
county building; is that right?
Mr. Walthers. I was standing right here.
Mr. Liebeler. You were standing over on Main Street just east of
the intersection of Main Street and Houston; is that correct?
Mr. Walthers. Yes; just between the two buildings.
Mr. Liebeler. Were you standing there when the motorcade came
down?
Mr. Walthers. Yes.
Mr. Liebeler. And you stood there and watched the motorcade go
by?
Mr. Walthers. Yes, sir.
Mr. Liebeler. Were you acting in any official capacity at that time?
Mr. Walthers. I was a deputy sheriff—I was on duty and had
stopped there with Mrs. Decker to watch the parade go by.
Mr. Liebeler. You didn't have any specific assignment in
connection with the motorcade or the President or anything like
that?
Mr. Walthers. No, sir.
Mr. Liebeler. The motorcade came down Main Street and made a
wide turn into Houston Street and went back down Elm Street; isn't
that right?
Mr. Walthers. Yes.
Mr. Liebeler. After the motorcade turned onto Houston Street,
what did you do?
Mr. Walthers. After it turned onto Houston and most of the
motorcade went by, I turned to talk to Mrs. Decker and asked her if
she was ready to go back inside and I proceeded to help her back
up the steps and then we heard the shots.
Mr. Liebeler. You actually were still standing over on Main Street
around the corner from Houston Street when you heard the shots?
Mr. Walthers. Yes, sir.
Mr. Liebeler. You actually didn't see any of the shots take effect
or anything like that?
Mr. Walthers. No.
Mr. Liebeler. How many shots did you hear?
Mr. Walthers. I remember three shots.
Mr. Liebeler. Are you clear about that?
Mr. Walthers. Yes, sir.
Mr. Liebeler. What did you do after you heard the shots?
Mr. Walthers. Well, I was facing her and I told her that sounded
like a rifle and I ran across here [indicating] and there is a wall along
in here and I hopped over it.
Mr. Liebeler. You mean you ran across Houston Street and
jumped over the wall and back into Dealey Plaza there?
Mr. Walthers. People were laying down on this grass—women
and men were laying on top of their children on the grass.
Mr. Liebeler. On either side of Main Street?
Mr. Walthers. Yes; and then someone, I don't know, I say
someone—a lot of people was sitting there—but it must have been
behind that fence—there's a fence right along here——
Mr. Liebeler. You are referring to the area immediately behind the
No. 7 that appears on Commission Exhibit No. 354—there is a
concrete structure there of some sort.
Mr. Walthers. It don't show on this, but since this picture was
made, there's a fence—it may be there—it's a solid board fence
along here.
Mr. Liebeler. Running along behind the concrete structure that
faces Elm Street and is No. 7 on Commission Exhibit No. 354?
Mr. Walthers. And at that time I heard the shots as well as
everybody else, but as we got over this fence, and a lot of officers
and people were just rummaging through the train yards back in this
parking area.
Mr. Liebeler. In the parking area down there? West of the Texas
School Book Depository Building between the Texas School Book
Depository and the railroad tracks?
Mr. Walthers. Yes; and the discussion came up among several of
the officers, Were there any shots fired? And I said, "Well, they
sounded like rifle shots to me." At the time no one knew—in our
crowd they were sure the shots had been fired though because of
the reports—we heard the noise, and I left then and went back up
here and came back onto the street.
Mr. Liebeler. Up on Elm Street?
Mr. Walthers. And went over on this grassy area right in here
[indicating].
Mr. Liebeler. Between Elm Street and Main Street?
Mr. Walthers. Between Elm and Main and starting to looking at
the grass to see if some shots had been fired and some of them
might have chugged into this turf here and it would give an
indication if some had really been, if they were really shots and not
just blanks or something, and a man, and I couldn't tell you his
name if my life depended on it—he had a car parked right here in
Main Street—in the Main Street lane headed east, just under this
underpass.
Mr. Liebeler. Down at the point marked No. 9 of the exhibit we
are talking about; is that right?
Mr. Walthers. That's right—in this lane here and his car was just
partially sticking out parked there and he came up to me and asked
me, he said, "Are you looking to see where some bullets may have
struck?" And I said, "Yes." He says, "I was standing over by the bank
here, right there where my car is parked when those shots
happened," and he said, "I don't know where they came from, or if
they were shots, but something struck me on the face," and he said,
"It didn't make any scratch or cut and it just was a sting," and so I
had him show me right where he was standing and I started to
search in that immediate area and found a place on the curb there in
the Main Street lane there close to the underpass where a projectile
had struck that curb.
Mr. Liebeler. Would you remember that man's name if I told you
or if I reminded you of it?
Mr. Walthers. I'm sorry—I don't know if I would remember it or
not.
Mr. Liebeler. There is a man by the name of Jim Tague [spelling],
T-a-g-u-e, who works as an automobile salesman.
Mr. Walthers. I remember he had a gray automobile—I
remember that very well.
Mr. Liebeler. I think it must have been Mr. Tague because he was
in here this afternoon and he told me his car was parked right there
at No. 9 and that's when I put the mark on the exhibit and he
walked up there and talked to a deputy sheriff and he looked at the
curb.
Mr. Walthers. Yes; this was pure ignorance on my part in not
getting his name—I don't know—but I didn't.
Mr. Liebeler. I think it is pretty clear it was Mr. Tague, because his
testimony he gave today jibed with yours and it couldn't have been
anybody else and he had a cut and some blood on his face.
Mr. Walthers. Well, at the time I wasn't interested in whether he
was cut or what, I just said, "Where were you standing?" In an
effort to prove there was some shots fired, and after seeing the way
it struck the curb at an angle—which it came down on the curb—it
was almost obvious that it either came from this building or this
building [indicating] the angle it struck the curb at.
Mr. Liebeler. When you say this building or this building you are
talking about the School Book Depository Building or the building
immediately east thereof, across Houston Street?
Mr. Walthers. Yes; and I ran right then back up along in here and
that would be right at the corner of Elm and Houston, where I ran
into one of our deputies, Allan Sweatt, and told him—everybody still
at this time was just—I don't know what you would call it—just
running around in circles you might say, and I told him, I said, "A
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like