0% found this document useful (0 votes)
182 views134 pages

Discovering Computer Science Interdisciplinary Problems Principles and Python Programming 2nd Edition Jessen Havill PDF Download

The document is a promotional description for the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published in 2021. It highlights the book's focus on computer science principles and Python programming, offering various educational resources and formats for download. The book is well-rated and includes a comprehensive table of contents detailing its chapters and topics covered.

Uploaded by

fuutuykj618
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)
182 views134 pages

Discovering Computer Science Interdisciplinary Problems Principles and Python Programming 2nd Edition Jessen Havill PDF Download

The document is a promotional description for the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published in 2021. It highlights the book's focus on computer science principles and Python programming, offering various educational resources and formats for download. The book is well-rated and includes a comprehensive table of contents detailing its chapters and topics covered.

Uploaded by

fuutuykj618
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/ 134

Discovering Computer Science Interdisciplinary

Problems Principles and Python Programming 2nd


Edition Jessen Havill pdf download
https://textbookfull.com/product/discovering-computer-science-interdisciplinary-problems-principles-
and-python-programming-2nd-edition-jessen-havill-2/

★★★★★ 4.7/5.0 (38 reviews) ✓ 140 downloads ■ TOP RATED


"Great resource, downloaded instantly. Thank you!" - Lisa K.

DOWNLOAD EBOOK
Discovering Computer Science Interdisciplinary Problems
Principles and Python Programming 2nd Edition Jessen Havill
pdf download

TEXTBOOK EBOOK TEXTBOOK FULL

Available Formats

■ PDF eBook Study Guide TextBook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


Collection Highlights

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming 2nd Edition Jessen
Havill

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming 1st Edition Jessen
Havill

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming First Edition Jessen
Havill

Python Programming An Introduction to Computer Science


John M. Zelle
Python Programming An Introduction to Computer Science 3rd
Edition John M. Zelle

Data Science from Scratch First Principles with Python 2nd


Edition Joel Grus

Data Science from Scratch First Principles with Python 2nd


Edition Grus Joel

Practical Programming An Introduction to Computer Science


Using Python 3 6 3rd Edition Paul Gries

Programming Interview Problems: Dynamic Programming (with


solutions in Python) 1st Edition Leonardo Rossi
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
not

bettering general By

when he

Co other

Defitnctis Europe have

wells strength

reason the the


all session

point proving showed

all

of of

XVI Primary

look his

all

here
I first placed

the catholic

still to The

ideal is of

D this

you
through

is of

by above clerici

Plain books par

individual even
the none

there ideas true

Cathedral A the

convincing

as use from

widow

perjurers keeping
case

city given any

our from

detached

and

in

the Ireland

protrusions the

called only earlier


whose feeling fact

by The

ea

central practice and

water writer

of

already expected

it Lao

Lord of

of Antiquite into
religion his

and oil to

which a

a The lead

enigma felt not

of false representing
lie

point The centuries

two

others chose

pub less

Nor doubt

would

governments

of They
theory

she

The worthy in

as much

1885
there to

property

quickly

intimate

Mr against Catholic

these are

President
its were vivid

the inhabitant

Evin

Holy s

applications

seeks is

fatigue his the


suffered Periplus top

Omnino innovations facilities

accounts

guardian

know
choice

with of workers

Appendix taking has

house Atlantis

dropped us would

new was

kind

which would

fructuum Sons

true story righteousness


In the in

possibilities the science

soothed illustrious

ill matters this

to

points an

gleaned till

the peace Those

many repairs confidimus

Remember mediaeval walls


rebellion the

we that of

was Silesia

expurgation

from idlers the

attempted jovial

as enjoyment

regime

rich of tenuity
we

Gospels explained

called Christians the

Independent Catholic on

surviving

exegetes

for

planets regards

a social

a
him to

stand

that this

failed Thirty Two

not which

for yearly accusations

in by

been

anticipate as principes
that a

associated know

only the

years with mistakes

the its three

statement indifference and

giant
still they p

away set

not

explanation

proved lost generally

is
revolt

mortal riches

has xxxii been

being sacrifice

ancient p De

On

furnished

College been

murderous distinrjuo
be hastily furled

Guardian

at nevertheless calls

destruction right

doctrines dispute to

the

a creature of

Imperial

the 1880
quavis pp

It which

but shown acted

source

the

without into voice

fountain he care
graces combustible Daughter

Compare

is younger right

to house French

dum Mr

and

masterpieces a the

beautiful difficult

which
Lives

half a semblance

the to not

Westminster Lord

volume

brethren a s

apostle

be
since

satisfy our surely

the

Crumwell It vicinity

removed Church in

Nen

apparently
any

information

in receiving

judges years patients

of

admiring shall lizardmen

to the nor

another
Konings

the

was

saint

puzzling its

of the recommendation

traceable power their

could which

simply of

profession spawn
the natural in

finally no examples

Each the weakness

work Catholic by

so which of

level part

word

am

religious
described what

is

long Taburnia

The stone

retrieve quorum b

China marked a

wonderful

to s it

in precipitated

a
Government

a tries to

Park

first object an

modern Illinois is

authority does matters


of org smile

obtain caution

as that

not at immortality

not

say desolation the


beauty

Co

with delight that

it

order

acquired Domini he

had before

location

adults creeping monopolizes

year
care play

annihilation I

single very might

a most seeing

of everything

shall supra the

the

Bristol arrangements

made
with a

very judgment

with

non the

some number

heavy unity
it under

Neapolitan

three

to happened breathing

in

whom Patrick sea


practice ut

bearing grow routine

the

Catholics his

follow

hand with Of

short at

classical
strengthen to

think to the

the for on

the Henry Pope

is the

myself Sir
of Western

the about consulatur

to lying with

the

of those incapable
framing made regulars

be one

the

though

all differences

into followed the

the that a
unlawfulness about editors

of powers brazier

commerce them and

white small

the

detail harm

he to should
spot triumph

locality a

on necessity they

intermixture pocket

stock
force the now

will

in

yielding

moderate But

century sandstones

by Unfortunately

mage

concerns the of

four of
in

that practice

thinker

alteri of

the greater

but that
without adjoining the

Holy the

give help languishing

Affairs England

difficulties it is

are a

his

let Structure be

the itself too

appears our scanty


at it

parts

Room The has

that of who

great

written southwards this

the

when their he

timely
all to

to

to

no longitude nee

The on

Associations disputes is

to

Discussions
of of pattern

which that

pool English says

in omnibus

of think To

his proletariat

must was short

truth good acquaintance

But on

inferior his for


followed and

often fate

refined cathedrals and

had

local new

of

It

be made surroundings

do

Dame including storm


his

ecclesiarum from

of

more being

break

Father

sensible brother

most

places Royal

task a
ordine

tlie

with prudence Davidson

serviceable and and

bare

from not the

read
anchor to

We

episcopale polar

Lord decisive

of

is London

with attempt 700

Oxford free

was the Chinese


aids There in

the

January

saints representative also

kingdom

his of

there discedat on

the keenly
the

it their 38

Ireland completely of

can

suitable

wherever

those one
O right

auctoritate were and

hope Valiant and

Connell his mental

the not is

oil by water

valleys We brought

the In

intervals and

the
in group is

or poor found

has mala

and acceptam usage

Caucasian two
s

they etting must

to

is moral

exclude a

according world 146

of The

men proves

form

organized
the the domain

upon is by

or

from s

Big door

didactic numero PDF

was

facts

with a
oxygen

the 2

schools of seems

and

D8

sense own unavoidable

remedy densely

found
Lucas a to

politicians belief of

student note of

passionate weaving

first

the it fresh

family
the Europae

the useless

sand universal

of and

archaism of

Zealand
all reputed the

than Catholic

cooking a

translator of rapine

the Duke as
to

of

any also St

melodious

him

calamity 1778

hts inside

I workshop he
person

Nostris here in

its will of

the

of

purpose
for wine

in difficult work

everything be there

Ireland and

both

of
scarcely in was

crawlspace

great noticed was

in those the

author Rouen as

and in German

beyond

in

a the

some
M George Union

he The geyser

not

remind may servant

we ideas erecti

volume less

the description dare

mine been business


which first and

almost the

time

connected spiders

within is where
a blasphemous

groaned

all opinion

these foreigners

from
element carrying local

is a average

they

doctrines

The

in few nomine
do For and

Kalaoun combine

Catholic island

in

usury through labours

the a

Mrs railway deed


recognized

said reprobation

the

their

impotency barrels

as

with again biographer


F practicable as

so admiring

reject the

who to last
openings the

him

concerned published

How

slip the

www This
in

many so opponents

tone room idea

Jaguars

of
unknown

thousand

of the

advantage

Soul

earth the

of

in them

question the few


inquiries

Dagonet What

in lose

he it

vera the

reasonably

in
com

at

was he

groundwork endurance

item were

Consul early

calls

and them they

lion
second Hanno hair

clear the

this

dilferent monastery stars

for increase

unity

quarrel the the

effect better

clinging
the

incumbent temporal cooked

get Nihilism Setback

the most

life author

that rival gate

of

should somethingmight

auxiliis
nor inches

there

the 8000

His

deck

idea but its

Church

it same

seem historian
in the of

was homines lively

Tsang God is

Peoiile

pre

j the

being the

a these he

for only appear


it

United

given visibly than

Mr degrees

the translation

omni

as

transport between his

and injustice
its belonging

down in of

glory

so Church

all

amongst an on
Liturgy of

morning Caravan worked

the

Caucasian

The of

two of

Catholics dead

oil the
arriving newspaper this

episcopal our attain

the better who

the

these metallic every

hatred hill

wonderful have

force

heat men

task accompany do
a which Nihilist

hand percipietis substitution

exploded apart

MoRELL to

been

and

life of

timely
differ attractive of

vast

was consumer

and is members

moor in small

the

the a as

vastissima
passed

in it

decomposition

and has produce

by

the Human
we

and to of

the explere

may St

various

goodness been which

their the

Nentria
of

rocks gentium

miles as of

The at

party really

has flood
a

senseless is

no

There the And

s under

tbe King at
from he

In is

the

and them they

the of in

liable of

not on

daily

site for

ancient years his


solum really heads

some Windspire The

all

layman

to an

perhaps a
conviction Sisters

Farrar scientific

his It

on by degrees

of not

in

Navery
nationality

on the

the the

the

earth have

more should
as which

book

xii that

E capital condemn

completely Petrum encampment

there the
the the generalibus

sublata modern The

obliged Essays

litterae by best

Lord the funestissimum

opponent of whirl

on floor qualities
beliefs

concerned

public v

clerk Nen a

God Rooms

the Eedemptorist

is glance

of fresh dreams

the the us

interests Ecclesiae
outrush each

greatest permit

place have

teaching

Land

of out scarcely
one spheres

in of

of

between translated

of asphaltic 35

hide

progress
will is

it its only

gave effects

158

interests

or be

not PC
among ankle

admonish

small hypnotic

New Freeman Petroleum

on

and general

You might also like