0% found this document useful (0 votes)
3 views57 pages

Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming 2nd Edition Jessen Havill download

The document is about the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published by CRC Press in 2021. It covers various topics in computer science and Python programming, including problem-solving, data visualization, and algorithms. The text also includes references to additional resources and related textbooks.

Uploaded by

pddjidak795
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 views57 pages

Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming 2nd Edition Jessen Havill download

The document is about the second edition of 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, published by CRC Press in 2021. It covers various topics in computer science and Python programming, including problem-solving, data visualization, and algorithms. The text also includes references to additional resources and related textbooks.

Uploaded by

pddjidak795
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/ 57

Discovering Computer Science: Interdisciplinary

Problems, Principles, and Python Programming 2nd


Edition Jessen Havill download

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

Download full version ebook from https://textbookfull.com


We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming 2nd Edition Jessen
Havill

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

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming 1st Edition Jessen
Havill

https://textbookfull.com/product/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

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

Biota Grow 2C gather 2C cook Loucas

https://textbookfull.com/product/biota-grow-2c-gather-2c-cook-
loucas/
Python Programming An Introduction to Computer Science
John M. Zelle

https://textbookfull.com/product/python-programming-an-
introduction-to-computer-science-john-m-zelle/

Python Programming An Introduction to Computer Science


3rd Edition John M. Zelle

https://textbookfull.com/product/python-programming-an-
introduction-to-computer-science-3rd-edition-john-m-zelle/

Data Science from Scratch First Principles with Python


2nd Edition Joel Grus

https://textbookfull.com/product/data-science-from-scratch-first-
principles-with-python-2nd-edition-joel-grus/

Data Science from Scratch First Principles with Python


2nd Edition Grus Joel

https://textbookfull.com/product/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

https://textbookfull.com/product/practical-programming-an-
introduction-to-computer-science-using-python-3-6-3rd-edition-
paul-gries/
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/CANDHTEXCOMSER?
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 information
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 [email protected]
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

Acknowledgments

About the author

CHAPTER 1 ■ How to Solve It

1.1 UNDERSTAND THE PROBLEM


A first problem: computing reading level
Functional abstraction

1.2 DESIGN AN ALGORITHM


Take it from the top
Pseudocode
Implement from the bottom

1.3 WRITE A PROGRAM


Welcome to the circus
What’s in a name?
Interactive computing
Looking ahead

1.4 LOOK BACK


Testing
Algorithm efficiency

1.5 SUMMARY AND FURTHER DISCOVERY

CHAPTER 2 ■ Visualizing Abstraction


2.1 DATA ABSTRACTION
Turtle graphics

2.2 DRAWING FLOWERS AND PLOTTING EARTHQUAKES


Iteration
Tangent 2.1 Defining colors
Data visualization

2.3 FUNCTIONAL ABSTRACTION


Function parameters

2.4 PROGRAMMING IN STYLE


Program structure
Documentation
Tangent 2.2 Global variables
Self-documenting code

2.5 A RETURN TO FUNCTIONS


The math module
Writing functions with return values
Return vs. print

2.6 SCOPE AND NAMESPACES


Local namespaces
The global namespace

2.7 SUMMARY AND FURTHER DISCOVERY

CHAPTER 3 ■ Inside a Computer

3.1 COMPUTERS ARE DUMB


Tangent 3.1 High performance computing
Machine language
Tangent 3.2 Byte code

3.2 EVERYTHING IS BITS


Bits are switches
Bits can represent anything
Tangent 3.3 Hexadecimal notation
Computing with bits

3.3 COMPUTER ARITHMETIC


Limited precision
Tangent 3.4 Floating point notation
Error propagation
Division
Complex numbers

*3.4 BINARYARITHMETIC
More limited precision
Negative integers
Designing an adder
Implementing an adder

3.5 THE UNIVERSAL MACHINE

3.6 SUMMARY AND FURTHER DISCOVERY

CHAPTER 4 ■ Growth and Decay

4.1 ACCUMULATORS
Managing a fishing pond
Measuring network value
Organizing a concert

4.2 DATA VISUALIZATION

4.3 CONDITIONAL ITERATION


When will the fish disappear?
When will your nest egg double?

*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
Tangent 4.1 Triangular numbers

4.7 FURTHER DISCOVERY

*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

5.1 RANDOM WALKS


Tangent 5.1 Interval notation
One small step
Monte Carlo simulation

*5.2 PSEUDORANDOM NUMBER GENERATORS


Implementation
Testing randomness

*5.3 SIMULATING PROBABILITY DISTRIBUTIONS


The central limit theorem

5.4 BACK TO BOOLEANS


Predicate functions
Short circuit evaluation
DeMorgan’s laws
Thinking inside the box
Many happy returns

5.5 DEFENSIVE PROGRAMMING


Checking parameters
Assertions
Unit testing
Tangent 5.2 Unit testing frameworks
Testing floats
Catching exceptions

5.6 GUESS MYNUMBER


Ending the game nicely
Friendly hints
A proper win/lose message

5.7 SUMMARY AND FURTHER DISCOVERY

*5.8 PROJECTS
5.1 The magic of polling
5.2 Escape!

CHAPTER 6 ■ Text, Documents, and DNA

6.1 FIRST STEPS


Normalization
Tangent 6.1 Natural language processing
Tokenization
Creating your own module
Testing your module

6.2 TEXT DOCUMENTS


Reading from text files
Writing to text files
Reading from the web

6.3 ENCODING STRINGS


Computing checksums
Unicode
Tangent 6.2 Compressing text files
Indexing and slicing

6.4 A CONCORDANCE
Finding a word
A concordance entry
A complete concordance

6.5 WORD FREQUENCY TRENDS


Finding the frequency of a word
Getting the frequencies in slices
Plotting the frequencies

6.6 COMPARING TEXTS


Dot plots

*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


*6.10 PROJECTS
6.1 Polarized politics
6.2 Finding genes

CHAPTER 7 ■ Data Analysis

7.1 SUMMARY STATISTICS


Mean and variance
Minimum and maximum

7.2 WRANGLING DATA


Smoothing data
A more efficient algorithm
Modifying lists in place
List operators and methods
*List comprehensions
Tangent 7.1 NumPy arrays

7.3 TALLYING FREQUENCIES


Word frequencies
Dictionaries
Tangent 7.2 Hash tables
Finding the most frequent word
Bigram frequencies
Tangent 7.3 Sentiment analysis

7.4 READING TABULAR DATA


Earthquakes

*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


Tangent 7.4 Privacy in the age of big data

*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
7.7 Heuristics for traveling salespeople

CHAPTER 8 ■ Flatland

8.1 TABULAR DATA


Reading a table of temperatures
Tangent 8.1 Pandas

8.2 THE GAME OF LIFE


Creating a grid
Initial configurations
Surveying the neighborhood
Performing one pass
Tangent 8.2 NumPy arrays in two dimensions
Updating the grid
8.3 DIGITAL IMAGES
Colors
Tangent 8.3 Additive vs. subtractive color models
Image filters
Tangent 8.4 Image storage and compression
Transforming images

8.4 SUMMARY AND FURTHER DISCOVERY

*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

9.1 FRACTALS
Trees
Snowflakes

9.2 RECURSION AND ITERATION


Solving a problem recursively
Palindromes
Guessing passwords

9.3 THE MYTHICAL TOWER OF HANOI


*Is the end of the world nigh?

9.4 RECURSIVE LINEAR SEARCH


*Efficiency of recursive linear search

9.5 DIVIDE AND CONQUER


Buy low, sell high
Navigating a maze
*9.6 LINDENMAYER SYSTEMS
Formal grammars
L-systems
Implementing L-systems

9.7 SUMMARY AND FURTHER DISCOVERY

*9.8 PROJECTS
9.1 Lindenmayer’s beautiful plants
9.2 Gerrymandering
9.3 Percolation

CHAPTER 10 ■ Organizing Data

10.1 BINARY SEARCH


Tangent 10.1 Databases
Efficiency of iterative binary search
A spelling checker
Recursive binary search
*Efficiency of recursive binary search

10.2 SELECTION SORT


Implementing selection sort
Efficiency of selection sort
Querying data

10.3 INSERTION SORT


Implementing insertion sort
Efficiency of insertion sort

10.4 EFFICIENT SORTING


Merge sort
Internal vs. external sorting
Efficiency of merge sort
*10.5 TRACTABLE AND INTRACTABLE ALGORITHMS
Hard problems

10.6 SUMMARY AND FURTHER DISCOVERY

*10.7 PROJECTS
10.1 Creating a searchable database
10.2 Binary search trees

CHAPTER 11 ■ Networks

11.1 MODELING WITH GRAPHS


Making friends

11.2 SHORTEST PATHS


Breadth-first search
Finding the actual paths

11.3 IT’S A SMALL WORLD…


Small world networks
Clustering coefficients
Scale-free networks

11.4 RANDOM GRAPHS

11.5 SUMMARYAND FURTHER DISCOVERY

*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

12.1 SIMULATING AN EPIDEMIC


Object design
Person class
Augmenting the Person class
World class
The simulation

12.2 OPERATORS AND POLYMORPHISM


Designing a Pair ADT
Pair class
Arithmetic methods
Special methods
Comparison operators
Indexing

*12.3 A FLOCKING SIMULATION


The World
Boids

*12.4 ASTACKADT
Stack class
Reversing a string
Converting numbers to other bases

*12.5 ADICTIONARYADT
Hash tables
Implementing a hash table Indexing
ADTs vs. data structures

12.6 SUMMARYAND FURTHER DISCOVERY

*12.7 PROJECTS
12.1 Tracking GPS coordinates
12.2 Economic mobility
12.3 Slime mold aggregation
12.4 Boids in space
Bibliography

APPENDIX A ■ Python Library Reference

APPENDIX B ■ Selected Exercise Solutions

Index
_______________
* Sections with *** in lieu of a page number are available on the book website.
Preface

n my view, an introductory computer science course should strive to accomplish three


I 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. 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 framework. 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 eliminated, 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.

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. However, it


does assume a modest comfort with high school algebra. In optional sections, 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 homework, 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 and interests. As
illustrated in Figure 1, Chapter 1, Chapter 2, Chapter 3, Chapter 4, Chapter 5, Chapter 6,
Chapter 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 Chapter 8, Chapter 9, Chapter 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.
Figure 1 An overview of chapter dependencies.

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, • functional abstraction • arithmetic
words
• sphere volume • functional decomposition • assignment
• digital music • top-down design • variable names
• search engines • bottom-up • calling built-in
implementation 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

2 Visualizing Abstraction
Sample problems Principles Programming
• visualizing • using abstract data types • using classes and objects
earthquakes
• 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 sampling • using distributions • Boolean operators
• 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

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 • histograms • list class
frequencies
• smoothing data • hash tables • indexing and slicing
• 100-year floods • tabular data files • list operators and
methods
• traveling salesman • efficient algorithm • reading CSV files
design
• 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

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 [email protected].
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.
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.
Exploring the Variety of Random
Documents with Different Content
But are not these spirited natures apt to be savage with one
another, and with everybody else? 57

A difficulty by no means easy to overcome, he replied.


C Whereas, I said, they ought to be dangerous to their enemies,
and gentle to their friends; if not, they will destroy themselves
without waiting for their enemies to destroy them.
True, he said.
What is to be done then? I said; how shall we find a gentle nature
which has also a great spirit, for the one is the contradiction of the
other?
True.
He will not
The guardian must unite the opposite qualities of gentleness and spirit.
be a good guardian who is wanting in either of these two qualities;
and yet the combination of them D appears to be impossible; and
hence we must infer that to be a good guardian is impossible.
I am afraid that what you say is true, he replied.
Here feeling perplexed I began to think over what had preceded.—
My friend, I said, no wonder that we are in a perplexity; for we have
lost sight of the image which we had before us.
What do you mean? he said.
I mean to say that there do exist natures gifted with those
opposite qualities.
And where do you find them?
Many animals, I replied,
Such a combination may be observed in the dog.
furnish examples of them; our E friend the dog is a very good one:
you know that well-bred dogs are perfectly gentle to their familiars
and acquaintances, and the reverse to strangers.
Yes, I know.
Then there is nothing impossible or out of the order of nature in
our finding a guardian who has a similar combination of qualities?
Certainly not.
Would not he who is fitted to be a guardian, besides the spirited
nature, need to have the qualities of a philosopher?
I do not apprehend your meaning.
376 The trait of which I am speaking, I replied, may be also seen
in the dog, and is remarkable in the animal.
What trait?
The dog distinguishes friend and enemy by the criterion of knowing and not knowing:
Why, a dog, whenever he sees a stranger, is angry; when an
acquaintance, he welcomes him, although the one has 58 never
done him any harm, nor the other any good. Did this never strike
you as curious?
The matter never struck me before; but I quite recognise the truth
of your remark.
And surely this instinct of the dog is very charming;— B your dog
is a true philosopher.
Why?
Why, because he distinguishes the face of a friend and of an
enemy only by the criterion of knowing and not knowing. And must
not an animal be a lover of learning who determines what he likes
and dislikes by the test of knowledge and ignorance?
Most assuredly.
And is not the love of learning the
whereby he is shown to be a philosopher.
love of wisdom, which is philosophy?
They are the same, he replied.
And may we not say confidently of man also, that he who C is
likely to be gentle to his friends and acquaintances, must by nature
be a lover of wisdom and knowledge?
That we may safely affirm.
Then he who is to be a really good and noble guardian of the
State will require to unite in himself philosophy and spirit and
swiftness and strength?
Undoubtedly.
Then we have found the
How are our citizens to be reared and educated?
desired natures; and now that we have found them, how are they to
be reared and educated? Is not this an enquiry which may be
expected to throw light D on the greater enquiry which is our final
end—How do justice and injustice grow up in States? for we do not
want either to omit what is to the point or to draw out the argument
to an inconvenient length.
Adeimantus thought that the enquiry would be
SOCRATES, ADEIMANTUS.
of great service to us.
Then, I said, my dear friend, the task must not be given up, even
if somewhat long.
Certainly not.
Come then, and let us pass a leisure hour in story-telling, and our
story shall be the education of our heroes.
E By all means.

And what shall be their education? Can we find a better 59 than


the traditional sort?—and this has two divisions, gymnastic for the
body, and music for the soul.
True.
Education divided into gymnastic for the body and music for the soul. Music includes
literature, which may be true or false. Shall we begin education with music,
and go on to gymnastic afterwards?
By all means.
And when you speak of music, do you include literature or not?
I do.
And literature may be either true or false?
Yes.
377 And the young should be trained in both kinds, and we begin
with the false?
I do not understand your meaning, he said.
You know, I said, that we begin by telling children stories which,
though not wholly destitute of truth, are in the main fictitious; and
these stories are told them when they are not of an age to learn
gymnastics.
Very true.
That was my meaning when I said that we must teach music
before gymnastics.
Quite right, he said.
You know also that the
The beginning the most important part of education.
beginning is the most important B part of any work, especially in
the case of a young and tender thing; for that is the time at which
the character is being formed and the desired impression is more
readily taken.
Quite true.
And shall we just carelessly allow children to hear any casual tales
which may be devised by casual persons, and to receive into their
minds ideas for the most part the very opposite of those which we
should wish them to have when they are grown up?
We cannot.
Then the first thing will be
Works of fiction to be placed under a censorship.
to establish a censorship of C the writers of fiction, and let the
censors receive any tale of fiction which is good, and reject the bad;
and we will desire mothers and nurses to tell their children the
authorised ones only. Let them fashion the mind with such tales,
even more fondly than they mould the body with their hands; but
most of those which are now in use must be discarded. 60

Of what tales are you speaking? he said.


You may find a model of the lesser in the greater, I said; D for
they are necessarily of the same type, and there is the same spirit in
both of them.
Very likely, he replied; but I do not as yet know what you would
term the greater.
Homer and Hesiod are tellers of bad lies, that is to say, they give false representations
Those, I said, which are narrated by Homer and Hesiod,
of the gods,
and the rest of the poets, who have ever been the great story-tellers
of mankind.
But which stories do you mean, he said; and what fault do you
find with them?
A fault which is most serious, I said; the fault of telling a lie, and,
what is more, a bad lie.
But when is this fault committed?
EWhenever an erroneous representation is made of the nature of
gods and heroes,—as when a painter paints a portrait not having the
shadow of a likeness to the original.
Yes, he said, that sort of thing is certainly very blameable; but
what are the stories which you mean?
First of all, I said, there was that greatest of all lies in high places,
which the poet told about Uranus, and which was a bad lie too,—I
mean what Hesiod says that Uranus did, 378 and how Cronus
retaliated on him8. The doings of Cronus, and the sufferings which in
turn his son inflicted upon him, even if they were true, ought
certainly not to be lightly told to young and thoughtless persons; if
possible, they had better be buried in silence. But if there is an
absolute necessity for their mention, a chosen few might hear them
in a mystery, and they should sacrifice not a common [Eleusinian]
pig, but some huge and unprocurable victim; and then the number
of the hearers will be very few indeed.
8 Hesiod, Theogony, 154, 459.

Why, yes, said he, those stories are extremely objectionable.


Yes, Adeimantus, they are
which have a bad effect on the minds of youth. B
stories not to be repeated in our State; the young man should not
be told that in committing the worst of crimes he is far from doing
anything outrageous; and that even if he chastises his father when
he does wrong, in whatever manner, he will only be following the
example of the first and greatest among the gods. 61
I entirely agree with you, he said; in my opinion those stories are
quite unfit to be repeated.
The stories about the quarrels of the gods and their evil behaviour to one another are
untrue. Neither, if we mean our future guardians to regard the habit
of quarrelling among themselves as of all things the basest, should
any word be said to them of the wars in heaven, C and of the plots
and fightings of the gods against one another, for they are not true.
No, we shall never mention the battles of the giants, or let them be
embroidered on garments; and we shall be silent about the
innumerable other quarrels of gods and heroes with their friends and
relatives. If they would only believe us we would tell them that
quarrelling is unholy, and that never up to this time D has there
been any quarrel between citizens; this is what old men and old
women should begin by telling children; and when they grow up, the
poets also should be told to compose for them in a similar spirit9.
But the narrative of Hephaestus binding Here his mother, or how on
another occasion Zeus sent him flying for taking her part when she
was being beaten, and all the battles of the gods in Homer— And
allegorical interpretations of them are not understood by the young. these tales must
not be admitted into our State, whether they are supposed to have
an allegorical meaning or not. For a young person cannot judge
what is allegorical and E what is literal; anything that he receives
into his mind at that age is likely to become indelible and
unalterable; and therefore it is most important that the tales which
the young first hear should be models of virtuous thoughts.
9 Placing the comma after γραυσί, and not after γιγνομένοις.

There you are right, he replied; but if any one asks where are
such models to be found and of what tales are you speaking—how
shall we answer him?
379 I said to him, You and I, Adeimantus, at this moment are not
poets, but founders of a State: now the founders of a State ought to
know the general forms in which poets should cast their tales, and
the limits which must be observed by them, but to make the tales is
not their business.
Very true, he said; but what are these forms of theology which
you mean?
Something of this kind, I replied:—
God is to be represented as he truly is.
God is always to be represented as he truly is, whatever be the sort
of poetry, epic, lyric or tragic, in which the representation is given.
Right. 62
BAnd is he not truly good? and must he not be represented as
such?
Certainly.
And no good thing is hurtful?
No, indeed.
And that which is not hurtful hurts not?
Certainly not.
And that which hurts not does no evil?
No.
And can that which does no evil be a cause of evil?
Impossible.
And the good is advantageous?
Yes.
And therefore the cause of well-being?
Yes.
It follows therefore that the good is not the cause of all things, but
of the good only?
C Assuredly.

Then God, if he be good, is


God, if he be good, is the author of good only.
not the author of all things, as the many assert, but he is the cause
of a few things only, and not of most things that occur to men. For
few are the goods of human life, and many are the evils, and the
good is to be attributed to God alone; of the evils the causes are to
be sought elsewhere, and not in him.
That appears to me to be most true, he said.
Then we must not listen to Homer or to any
The fictions of the poets.
other poet D who is guilty of the folly of saying that two casks

‘Lie at the threshold of Zeus, full of lots, one of good, the other of evil
lots10,’

and that he to whom Zeus gives a mixture of the two

‘Sometimes meets with evil fortune, at other times with good;’

but that he to whom is given the cup of unmingled ill,

‘Him wild hunger drives o’er the beauteous earth.’

E And again—
‘Zeus, who is the dispenser of good and evil to us.’

And if any one asserts that the violation of oaths and treaties, 63
which was really the work of Pandarus11, was brought about by
Athene and Zeus, or that the strife and contention of the gods was
instigated by Themis and Zeus12, he shall not have our approval;
neither will we allow our young men to hear the words of Aeschylus,
that

380 ‘God plants guilt among men when he desires utterly to destroy a
house.’

And if a poet writes of the sufferings of Niobe—the subject of the


tragedy in which these iambic verses occur—or of the house of
Pelops, or of the Trojan war or on any similar theme, either we must
not permit him to say that these are the works of God, or if they are
of God, he must devise some explanation of them such as we are
seeking; Only that evil which is of the nature of punishment to be attributed to God. he
must say that B God did what was just and right, and they were the
better for being punished; but that those who are punished are
miserable, and that God is the author of their misery—the poet is not
to be permitted to say; though he may say that the wicked are
miserable because they require to be punished, and are benefited by
receiving punishment from God; but that God being good is the
author of evil to any one is to be C strenuously denied, and not to
be said or sung or heard in verse or prose by any one whether old or
young in any well-ordered commonwealth. Such a fiction is suicidal,
ruinous, impious.
10 Iliad, xxiv. 527.

11 Iliad, ii. 69.

12 Ib. xx.

I agree with you, he replied, and am ready to give my assent to


the law.
Let this then be one of our rules and principles concerning the
gods, to which our poets and reciters will be expected to conform,—
that God is not the author of all things, but of good only.
That will do, he said.
DAnd what do you think of a second principle? Shall I ask you
whether God is a magician, and of a nature to appear insidiously
now in one shape, and now in another—sometimes himself changing
and passing into many forms, sometimes deceiving us with the
semblance of such transformations; or is he one and the same
immutably fixed in his own proper image? 64
I cannot answer you, he said, without more thought.
Well, I said; but if
Things must be changed either by another or by themselves.
we suppose a change in anything, that E change must be effected
either by the thing itself, or by some other thing?
Most certainly.
And things which are at their best are also least liable to be
altered or discomposed; for example, when healthiest and strongest,
the human frame is least liable to be affected by meats and drinks,
and the plant which is in the fullest vigour also suffers least from
winds or the heat of the sun or any similar causes.
Of course.
381And will not the bravest and wisest soul be least confused or
deranged by any external influence?
True.
And the same principle, as I should suppose, applies to all
composite things—furniture, houses, garments: when good and well
made, they are least altered by time and circumstances.
Very true.
B Then everything which is good, whether made by art or nature,
or both, is least liable to suffer change from without?
True.
But surely God and the things of God are in every way perfect?
Of course they are.
Then he
But God cannot be changed by other; and will not be changed by himself.
can hardly be compelled by external influence to take many shapes?
He cannot.
But may he not change and transform himself?
Clearly, he said, that must be the case if he is changed at all.
And will he then change himself for the better and fairer, or for the
worse and more unsightly?
CIf he change at all he can only change for the worse, for we
cannot suppose him to be deficient either in virtue or beauty.
Very true, Adeimantus; but then, would any one, whether God or
man, desire to make himself worse?
Impossible.
Then it is impossible that God should ever be willing to 65 change;
being, as is supposed, the fairest and best that is conceivable, every
God remains absolutely and for ever in his own form.
That necessarily follows, he said, in my judgment.
D Then, I said, my dear friend, let none of the poets tell us that

‘The gods, taking the disguise of strangers from other lands, walk up
and down cities in all sorts of forms13;’
and let no one slander Proteus and Thetis, neither let any one, either
in tragedy or in any other kind of poetry, introduce Here disguised in
the likeness of a priestess asking an alms

‘For the life-giving daughters of Inachus the river of Argos;’

E —let us have no more lies of that sort. Neither must we have


mothers under the influence of the poets scaring their children with
a bad version of these myths—telling how certain gods, as they say,
‘Go about by night in the likeness of so many strangers and in divers
forms;’ but let them take heed lest they make cowards of their
children, and at the same time speak blasphemy against the gods.
13 Hom. Od. xvii. 485.

Heaven forbid, he said.


But although the gods are themselves unchangeable, still by
witchcraft and deception they may make us think that they appear in
various forms?
Perhaps, he replied.
Well, but can you
Nor will he make any false representation of himself.
imagine that God will be willing to lie, whether in word or deed, or to
put forth a phantom of himself?
382 I cannot say, he replied.

Do you not know, I said, that the true lie, if such an expression
may be allowed, is hated of gods and men?
What do you mean? he said.
I mean that no one is willingly deceived in that which is the truest
and highest part of himself, or about the truest and highest matters;
there, above all, he is most afraid of a lie having possession of him.
66

Still, he said, I do not comprehend you.


B The reason is, I replied, that you attribute some profound
meaning to my words; but I am only saying that deception, or being
deceived or uninformed about the highest realities in the highest
part of themselves, which is the soul, and in that part of them to
have and to hold the lie, is what mankind least like;—that, I say, is
what they utterly detest.
There is nothing more hateful to them.
And, as I was just now remarking, this ignorance in the soul of
him who is deceived may be called the true lie; for the lie in words is
only a kind of imitation and shadowy image of a previous affection of
the soul, not pure unadulterated C falsehood. Am I not right?

Perfectly right.
The true lie is equally hated both by gods and men; the remedial or preventive lie is
comparatively innocent, but God can have no need of it. The true lie is hated not
only by the gods, but also by men?
Yes.
Whereas the lie in words is in certain cases useful and not hateful;
in dealing with enemies—that would be an instance; or again, when
those whom we call our friends in a fit of madness or illusion are
going to do some harm, then it is useful and is a sort of medicine or
preventive; also in the D tales of mythology, of which we were just
now speaking—because we do not know the truth about ancient
times, we make falsehood as much like truth as we can, and so turn
it to account.
Very true, he said.
But can any of these reasons apply to God? Can we suppose that
he is ignorant of antiquity, and therefore has recourse to invention?
That would be ridiculous, he said.
Then the lying poet has no place in our idea of God?
I should say not.
Or perhaps he may tell a lie because he is afraid of enemies?
E That is inconceivable.

But he may have friends who are senseless or mad?


But no mad or senseless person can be a friend of God.
Then no motive can be imagined why God should lie?
None whatever. 67
Then the superhuman and divine is absolutely incapable of
falsehood?
Yes.
Then is God perfectly simple and true both in word and deed14; he
changes not; he deceives not, either by sign or word, by dream or
waking vision.
14 Omitting κατὰ φαντασίας.

383 Your thoughts, he said, are the reflection of my own.

You agree with me then, I said, that this is the second type or
form in which we should write and speak about divine things. The
gods are not magicians who transform themselves, neither do they
deceive mankind in any way.
I grant that.
Then, although we are admirers
Away then with the falsehoods of the poets!
of Homer, we do not admire the lying dream which Zeus sends to
Agamemnon; neither will we praise the verses of Aeschylus in which
Thetis B says that Apollo at her nuptials
‘Was celebrating in song her fair progeny whose days were to be long,
and to know no sickness. And when he had spoken of my lot as in all
things blessed of heaven he raised a note of triumph and cheered my
soul. And I thought that the word of Phoebus, being divine and full of
prophecy, would not fail. And now he himself who uttered the strain, he
who was present at the banquet, and who said this—he it is who has slain
my son15.’

15 From a lost play.

C These are the kind of sentiments about the gods which will
arouse our anger; and he who utters them shall be refused a
chorus; neither shall we allow teachers to make use of them in the
instruction of the young, meaning, as we do, that our guardians, as
far as men can be, should be true worshippers of the gods and like
them.
I entirely agree, he said, in these principles, and promise to make
them my laws.
BOOK III.

Steph.
386 Republic III.
SOCRATES, ADEIMANTUS.
SUCH then, I said, are our principles of
The discouraging lessons of mythology.
theology—some tales are to be told, and others are not to be told to
our disciples from their youth upwards, if we mean them to honour
the gods and their parents, and to value friendship with one another.
Yes; and I think that our principles are right, he said.
But if they are to be courageous, must they not learn other
lessons besides these, and lessons of such a kind as will take
B away the fear of death? Can any man be courageous who has the
fear of death in him?
Certainly not, he said.
And can he be fearless of death, or will he choose death in battle
rather than defeat and slavery, who believes the world below to be
real and terrible?
Impossible.
Then we must assume a
The description of the world below in Homer.
control over the narrators of this class of tales as well as over the
others, and beg them not simply to revile but rather to commend the
world below, C intimating to them that their descriptions are untrue,
and will do harm to our future warriors.
That will be our duty, he said.
Then, I said, we shall have to obliterate many obnoxious
passages, beginning with the verses,
‘I would rather be a serf on the land of a poor and portionless man than
rule over all the dead who have come to nought1.’

We must also expunge the verse, which tells us how Pluto feared,

D ‘Lest the mansions grim and squalid which the gods abhor should be
seen both of mortals and immortals2.’ 69

And again:—

‘O heavens! verily in the house of Hades there is soul and ghostly form
but no mind at all3!’

Again of Tiresias:—

‘[To him even after death did Persephone grant mind,] that he alone
should be wise; but the other souls are flitting shades4.’

Again:—

‘The soul flying from the limbs had gone to Hades, lamenting her fate,
leaving manhood and youth5.’

Again:—

387 ‘And the soul, with shrilling cry, passed like smoke beneath the
earth6.’

And,—

‘As bats in hollow of mystic cavern, whenever any of them has dropped
out of the string and falls from the rock, fly shrilling and cling to one
another, so did they with shrilling cry hold together as they moved7.’
B And we must beg Homer and the other
Such tales to be rejected.
poets not to be angry if we strike out these and similar passages,
not because they are unpoetical, or unattractive to the popular ear,
but because the greater the poetical charm of them, the less are
they meet for the ears of boys and men who are meant to be free,
and who should fear slavery more than death.
1 Od. xi. 489.

2 Il. xx. 64.

3 Il. xxiii. 103.

4 Od. x. 495.

5 Il. xvi. 856.

6 Ib. xxiii. 100.

7 Od. xxiv. 6.

Undoubtedly.
Also we shall have to reject all the terrible and appalling names
which describe the world below—Cocytus and Styx, C ghosts under
the earth, and sapless shades, and any similar words of which the
very mention causes a shudder to pass through the inmost soul of
him who hears them. I do not say that these horrible stories may not
have a use of some kind; but there is a danger that the nerves of
our guardians may be rendered too excitable and effeminate by
them.
There is a real danger, he said.
Then we must have no more of them.
True.
Another and a nobler strain must be composed and sung by us. 70
Clearly.
D And shall we proceed to get rid of the weepings and wailings
of famous men?
They will go with the rest.
The effeminate and pitiful strains of famous men, and yet more of the gods, must also
be banished. But shall we be right in getting rid of them? Reflect: our
principle is that the good man will not consider death terrible to any
other good man who is his comrade.
Yes; that is our principle.
And therefore he will not sorrow for his departed friend as though
he had suffered anything terrible?
He will not.
Such an one, as we further maintain, is sufficient for himself
E and his own happiness, and therefore is least in need of other
men.
True, he said.
And for this reason the loss of a son or brother, or the deprivation
of fortune, is to him of all men least terrible.
Assuredly.
And therefore he will be least likely to lament, and will bear with
the greatest equanimity any misfortune of this sort which may befall
him.
Yes, he will feel such a misfortune far less than another.
Then we shall be right in getting rid of the lamentations of famous
men, and making them over to women (and not 388 even to women
who are good for anything), or to men of a baser sort, that those
who are being educated by us to be the defenders of their country
may scorn to do the like.
That will be very right.
Then we will once more entreat
Such are the laments of Achilles, and Priam,
Homer and the other poets not to depict Achilles8, who is the son of
a goddess, first lying on his side, then on his back, and then on his
face; then starting up and sailing in a frenzy along the shores of
B the barren sea; now taking the sooty ashes in both his hands9
and pouring them over his head, or weeping and wailing in the
various modes which Homer has delineated. Nor should he describe
Priam the kinsman of the gods as praying and beseeching,

‘Rolling in the dirt, calling each man loudly by his name10.’ 71

Still more earnestly will we beg of him at all events not to introduce
the gods lamenting and saying,

C ‘Alas! my misery! Alas! that I bore the bravest to my sorrow11.’

But if he must
and of Zeus when he beholds the fate of Hector or Sarpedon.
introduce the gods, at any rate let him not dare so completely to
misrepresent the greatest of the gods, as to make him say—

‘O heavens! with my eyes verily I behold a dear friend of mine chased


round and round the city, and my heart is sorrowful12.’

Or again:—

‘Woe is me that I am fated to have Sarpedon, dearest of D men to me,


subdued at the hands of Patroclus the son of Menoetius13.’

For if, my sweet Adeimantus, our youth seriously listen to such


unworthy representations of the gods, instead of laughing at them
as they ought, hardly will any of them deem that he himself, being
but a man, can be dishonoured by similar actions; neither will he
rebuke any inclination which may arise in his mind to say and do the
like. And instead of having any shame or self-control, he will be
always whining and lamenting on slight occasions.
8 Il. xxiv. 10.

9 Ib. xviii. 23.

10 Ib. xxii. 414.

11 Il. xviii. 54.

12 Ib. xxii. 168.

13 Ib. xvi. 433.

E Yes, he said, that is most true.

Yes, I replied; but that surely is what ought not to be, as the
argument has just proved to us; and by that proof we must abide
until it is disproved by a better.
It ought not to be.
Neither are the guardians to be encouraged to laugh by the example of the gods.
Neither ought our guardians to be given to laughter. For a fit of
laughter which has been indulged to excess almost always produces
a violent reaction.
So I believe.
Then persons of worth, even if only mortal men, must not be
represented as overcome by laughter, and still less must such a
representation of the gods be allowed.
389 Still less of the gods, as you say, he replied.

Then we shall not suffer such an expression to be used about the


gods as that of Homer when he describes how

‘Inextinguishable laughter arose among the blessed gods, when they saw
Hephaestus bustling about the mansion14.’

On your views, we must not admit them. 72


14 Ib. i. 599.

On my views, if you like to father them on me; that we B must


not admit them is certain.
Again, truth should be highly valued; if, as
Our youth must be truthful,
we were saying, a lie is useless to the gods, and useful only as a
medicine to men, then the use of such medicines should be
restricted to physicians; private individuals have no business with
them.
Clearly not, he said.
Then if any one at all is to have the privilege of lying, the rulers of
the State should be the persons; and they, in their dealings either
with enemies or with their own citizens, may be allowed to lie for the
public good. But nobody else should C meddle with anything of the
kind; and although the rulers have this privilege, for a private man to
lie to them in return is to be deemed a more heinous fault than for
the patient or the pupil of a gymnasium not to speak the truth about
his own bodily illnesses to the physician or to the trainer, or for a
sailor not to tell the captain what is happening about the ship and
the rest of the crew, and how things are going with himself or his
fellow sailors.
Most true, he said.
D If, then, the ruler catches anybody beside himself lying in the
State,

‘Any of the craftsmen, whether he be priest or physician or carpenter15,’

he will punish him for introducing a practice which is equally


subversive and destructive of ship or State.
15 Od. xvii. 383 sq.

Most certainly, he said, if our idea of the State is ever carried


out16.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like