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

Discovering Computer Science Interdisciplinary Problems Principles And Python Programming Havill download

The document provides information about the book 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, which is part of the Chapman & Hall/CRC Textbooks in Computing series. It outlines the book's aims, scope, and contents, covering various topics in computer science and programming. Additionally, it includes links to download different editions of the book and other related resources.

Uploaded by

saaloaljena45
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)
1 views

Discovering Computer Science Interdisciplinary Problems Principles And Python Programming Havill download

The document provides information about the book 'Discovering Computer Science: Interdisciplinary Problems, Principles, and Python Programming' by Jessen Havill, which is part of the Chapman & Hall/CRC Textbooks in Computing series. It outlines the book's aims, scope, and contents, covering various topics in computer science and programming. Additionally, it includes links to download different editions of the book and other related resources.

Uploaded by

saaloaljena45
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/ 84

Discovering Computer Science Interdisciplinary

Problems Principles And Python Programming


Havill download

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

Explore and download more ebooks at ebookbell.com


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

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming 2nd Edition Jessen Havill

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

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming 1st Edition Jessen Havill

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

Discovering Computer Science Interdisciplinary Problems Principles And


Python Programming First Edition Jessen Havill

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

Discovering Computer Science Havill Jessen

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

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

Discovering Computers Fundamentals Your Interactive Guide To The


Digital World Gary B Shelly

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

Discovering Computers Fundamentals 2011 Edition Shelly Cashman 7th


Edition Gary B Shelly

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

Discovering Computers Complete Your Interactive Guide To The Digital


World 1st Edition Gary B Shelly

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

Discovering Computers Fundamentals 5th Ed Gary B Shelly Misty E


Vermaat Contributing Authors

https://ebookbell.com/product/discovering-computers-fundamentals-5th-
ed-gary-b-shelly-misty-e-vermaat-contributing-authors-2620866
DISCOVERING
COMPUTER
SCIENCE
Interdisciplinary Problems,
Principles, and Python
Programming
CHAPMAN & HALL/CRC
TEXTBOOKS IN COMPUTING

Series Editors

John Impagliazzo Andrew McGettrick


Professor Emeritus, Hofstra University Department of Computer
and Information Sciences
University of Strathclyde

Aims and Scope

This series covers traditional areas of computing, as well as related technical areas, such as
software engineering, artificial intelligence, computer engineering, information systems, and
information technology. The series will accommodate textbooks for undergraduate and gradu-
ate students, generally adhering to worldwide curriculum standards from professional societ-
ies. The editors wish to encourage new and imaginative ideas and proposals, and are keen to
help and encourage new authors. The editors welcome proposals that: provide groundbreaking
and imaginative perspectives on aspects of computing; present topics in a new and exciting
context; open up opportunities for emerging areas, such as multi-media, security, and mobile
systems; capture new developments and applications in emerging fields of computing; and
address topics that provide support for computing, such as mathematics, statistics, life and
physical sciences, and business.

Published Titles

Paul Anderson, Web 2.0 and Beyond: Principles and Technologies


Henrik Bærbak Christensen, Flexible, Reliable Software: Using Patterns and Agile Development
John S. Conery, Explorations in Computing: An Introduction to Computer Science
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
Ted Herman, A Functional Start to Computing with Python
Pascal Hitzler, Markus Krötzsch, and Sebastian Rudolph, Foundations of Semantic Web
Technologies
Mark J. Johnson, A Concise Introduction to Data Structures using Java
Mark J. Johnson, A Concise Introduction to Programming in Python
Lisa C. Kaczmarczyk, Computers and Society: Computing for Good
Mark C. Lewis, Introduction to the Art of Programming Using Scala
Bill Manaris and Andrew R. Brown, Making Music with Computers: Creative Programming in
Python
Uvais Qidwai and C.H. Chen, Digital Image Processing: An Algorithmic Approach with MATLAB®
David D. Riley and Kenny A. Hunt, Computational Thinking for the Modern Problem Solver
Henry M. Walker, The Tao of Computing, Second Edition
Chapman & Hall/CRC
TEXTBOOKS IN COMPUTING

DISCOVERING
COMPUTER
SCIENCE
Interdisciplinary Problems,
Principles, and Python
Programming

Jessen Havill
Denison University
Granville, Ohio, USA
CRC Press
Taylor & Francis Group
6000 Broken Sound Parkway NW, Suite 300
Boca Raton, FL 33487-2742
© 2016 by Taylor & Francis Group, LLC
CRC Press is an imprint of Taylor & Francis Group, an Informa business

No claim to original U.S. Government works


Version Date: 20150318

International Standard Book Number-13: 978-1-4822-5416-7 (eBook - PDF)

This book contains information obtained from authentic and highly regarded sources. Reasonable efforts have been
made to publish reliable data and information, but the author and publisher cannot assume responsibility for the valid-
ity of all materials or the consequences of their use. The authors and publishers have attempted to trace the copyright
holders of all material reproduced in this publication and apologize to copyright holders if permission to publish in this
form has not been obtained. If any copyright material has not been acknowledged please write and let us know so we may
rectify in any future reprint.

Except as permitted under U.S. Copyright Law, no part of this book may be reprinted, reproduced, transmitted, or uti-
lized in any form by any electronic, mechanical, or other means, now known or hereafter invented, including photocopy-
ing, microfilming, and recording, or in any information storage or retrieval system, without written permission from the
publishers.

For permission to photocopy or use material electronically from this work, please access www.copyright.com (http://
www.copyright.com/) or contact the Copyright Clearance Center, Inc. (CCC), 222 Rosewood Drive, Danvers, MA 01923,
978-750-8400. CCC is a not-for-profit organization that provides licenses and registration for a variety of users. For
organizations that have been granted a photocopy license by the CCC, a separate system of payment has been arranged.

Trademark Notice: Product or corporate names may be trademarks or registered trademarks, and are used only for
identification and explanation without intent to infringe.
Visit the Taylor & Francis Web site at
http://www.taylorandfrancis.com
and the CRC Press Web site at
http://www.crcpress.com
Contents

Preface xv

Acknowledgments xxiii

About the author xxv

Chapter 1  What is computation? 1


1.1 PROBLEMS AND ABSTRACTION 2
1.2 ALGORITHMS AND PROGRAMS 4
1.3 EFFICIENT ALGORITHMS 11
Organizing a phone tree 11
A smoothing algorithm 13
A better smoothing algorithm 17
1.4 COMPUTERS ARE DUMB 20
Inside a computer 20
Machine language 21
Everything is bits 22
The universal machine 26
1.5 SUMMARY 29
1.6 FURTHER DISCOVERY 30

Chapter 2  Elementary computations 31


2.1 WELCOME TO THE CIRCUS 31
2.2 ARITHMETIC 32
Finite precision 34
Division 34
Order of operations 35
Complex numbers 37
2.3 WHAT’S IN A NAME? 38
2.4 USING FUNCTIONS 45

v
vi  Contents

Built-in functions 45
Strings 47
Modules 51
*2.5 BINARY ARITHMETIC 54
Finite precision 55
Negative integers 56
Designing an adder 57
Implementing an adder 58
2.6 SUMMARY 62
2.7 FURTHER DISCOVERY 62

Chapter 3  Visualizing abstraction 65


3.1 DATA ABSTRACTION 66
3.2 VISUALIZATION WITH TURTLES 70
Drawing with iteration 72
3.3 FUNCTIONAL ABSTRACTION 76
Function parameters 78
Let’s plant a garden 84
3.4 PROGRAMMING IN STYLE 89
Program structure 89
Documentation 91
Descriptive names and magic numbers 95
3.5 A RETURN TO FUNCTIONS 97
Return vs. print 100
3.6 SCOPE AND NAMESPACES 103
Local namespaces 104
The global namespace 107
3.7 SUMMARY 111
3.8 FURTHER DISCOVERY 112

Chapter 4  Growth and decay 113


4.1 DISCRETE MODELS 114
Managing a fishing pond 114
Measuring network value 121
Organizing a concert 124
4.2 VISUALIZING POPULATION CHANGES 136
4.3 CONDITIONAL ITERATION 140
Contents  vii

*4.4 CONTINUOUS MODELS 145


Difference equations 145
Radiocarbon dating 148
Tradeoffs between accuracy and time 150
Propagation of errors 152
Simulating an epidemic 153
*4.5 NUMERICAL ANALYSIS 159
The harmonic series 159
Approximating π 162
Approximating square roots 164
4.6 SUMMING UP 167
4.7 FURTHER DISCOVERY 171
4.8 PROJECTS 171
Project 4.1 Parasitic relationships 171
Project 4.2 Financial calculators 173
*Project 4.3 Market penetration 177
*Project 4.4 Wolves and moose 180

Chapter 5  Forks in the road 185


5.1 RANDOM WALKS 185
A random walk in Monte Carlo 192
Histograms 195
*5.2 PSEUDORANDOM NUMBER GENERATORS 200
Implementation 201
Testing randomness 203
*5.3 SIMULATING PROBABILITY DISTRIBUTIONS 205
The central limit theorem 206
5.4 BACK TO BOOLEANS 209
Short circuit evaluation 212
Complex expressions 214
*Using truth tables 216
Many happy returns 218
5.5 A GUESSING GAME 224
5.6 SUMMARY 233
5.7 FURTHER DISCOVERY 234
5.8 PROJECTS 234
viii  Contents

Project 5.1 The magic of polling 234


Project 5.2 Escape! 237

Chapter 6  Text, documents, and DNA 241


6.1 COUNTING WORDS 242
6.2 TEXT DOCUMENTS 250
Reading from text files 250
Writing to text files 253
Reading from the web 254
6.3 ENCODING STRINGS 259
Indexing and slicing 259
Creating modified strings 261
Encoding characters 263
6.4 LINEAR-TIME ALGORITHMS 270
Asymptotic time complexity 274
6.5 ANALYZING TEXT 279
Counting and searching 279
A concordance 284
6.6 COMPARING TEXTS 289
*6.7 GENOMICS 297
A genomics primer 297
Basic DNA analysis 301
Transforming sequences 302
Comparing sequences 304
Reading sequence files 306
6.8 SUMMARY 312
6.9 FURTHER DISCOVERY 313
6.10 PROJECTS 313
Project 6.1 Polarized politics 313
*Project 6.2 Finding genes 316

Chapter 7  Designing programs 321


7.1 HOW TO SOLVE IT 322
Understand the problem 323
Design an algorithm 324
Implement your algorithm as a program 327
Analyze your program for clarity, correctness, and efficiency 330
Contents  ix

*7.2 DESIGN BY CONTRACT 331


Preconditions and postconditions 331
Checking parameters 332
Assertions 334
*7.3 TESTING 340
Unit testing 340
Regression testing 342
Designing unit tests 343
Testing floating point values 347
7.4 SUMMARY 350
7.5 FURTHER DISCOVERY 350

Chapter 8  Data analysis 351


8.1 SUMMARIZING DATA 351
8.2 CREATING AND MODIFYING LISTS 360
List accumulators, redux 360
Lists are mutable 361
Tuples 365
List operators and methods 366
*List comprehensions 368
8.3 FREQUENCIES, MODES, AND HISTOGRAMS 373
Tallying values 373
Dictionaries 374
8.4 READING TABULAR DATA 384
*8.5 DESIGNING EFFICIENT ALGORITHMS 390
A first algorithm 391
A more elegant algorithm 399
A more efficient algorithm 400
*8.6 LINEAR REGRESSION 403
*8.7 DATA CLUSTERING 409
Defining similarity 410
A k-means clustering example 411
Implementing k-means clustering 414
Locating bicycle safety programs 416
8.8 SUMMARY 421
8.9 FURTHER DISCOVERY 421
x  Contents

8.10 PROJECTS 422


Project 8.1 Climate change 422
Project 8.2 Does education influence unemployment? 425
Project 8.3 Maximizing profit 427
Project 8.4 Admissions 428
*Project 8.5 Preparing for a 100-year flood 430
Project 8.6 Voting methods 435
Project 8.7 Heuristics for traveling salespeople 438

Chapter 9  Flatland 443


9.1 TWO-DIMENSIONAL DATA 443
9.2 THE GAME OF LIFE 449
Creating a grid 451
Initial configurations 452
Surveying the neighborhood 453
Performing one pass 454
Updating the grid 457
9.3 DIGITAL IMAGES 461
Colors 461
Image filters 463
Transforming images 467
9.4 SUMMARY 471
9.5 FURTHER DISCOVERY 471
9.6 PROJECTS 471
Project 9.1 Modeling segregation 471
Project 9.2 Modeling ferromagnetism 473
Project 9.3 Growing dendrites 474

Chapter 10  Self-similarity and recursion 477


10.1 FRACTALS 477
A fractal tree 479
A fractal snowflake 481
10.2 RECURSION AND ITERATION 488
Solving a problem recursively 491
Palindromes 492
Guessing passwords 495
10.3 THE MYTHICAL TOWER OF HANOI 500
Contents  xi

*Is the end of the world nigh? 502


10.4 RECURSIVE LINEAR SEARCH 503
Efficiency of recursive linear search 505
10.5 DIVIDE AND CONQUER 508
Buy low, sell high 508
Navigating a maze 512
*10.6 LINDENMAYER SYSTEMS 518
Formal grammars 518
Implementing L-systems 522
10.7 SUMMARY 525
10.8 FURTHER DISCOVERY 526
10.9 PROJECTS 526
*Project 10.1 Lindenmayer’s beautiful plants 526
Project 10.2 Gerrymandering 531
Project 10.3 Percolation 536

Chapter 11  Organizing data 541


11.1 BINARY SEARCH 542
Efficiency of iterative binary search 546
A spelling checker 548
Recursive binary search 549
Efficiency of recursive binary search 550
11.2 SELECTION SORT 553
Implementing selection sort 553
Efficiency of selection sort 557
Querying data 558
11.3 INSERTION SORT 563
Implementing insertion sort 564
Efficiency of insertion sort 566
11.4 EFFICIENT SORTING 570
Internal vs. external sorting 574
Efficiency of merge sort 574
*11.5 TRACTABLE AND INTRACTABLE ALGORITHMS 577
Hard problems 579
11.6 SUMMARY 580
11.7 FURTHER DISCOVERY 581
xii  Contents

11.8 PROJECTS 581


Project 11.1 Creating a searchable database 581
Project 11.2 Binary search trees 581

Chapter 12  Networks 587


12.1 MODELING WITH GRAPHS 588
Making friends 590
12.2 SHORTEST PATHS 594
Finding the actual paths 598
12.3 IT’S A SMALL WORLD. . . 601
Clustering coefficients 603
Scale-free networks 605
12.4 RANDOM GRAPHS 608
12.5 SUMMARY 611
12.6 FURTHER DISCOVERY 611
12.7 PROJECTS 612
Project 12.1 Diffusion of ideas and influence 612
Project 12.2 Slowing an epidemic 614
Project 12.3 The Oracle of Bacon 616

Chapter 13  Abstract data types 621


13.1 DESIGNING CLASSES 622
Implementing a class 625
Documenting a class 632
13.2 OPERATORS AND SPECIAL METHODS 637
String representations 637
Arithmetic 638
Comparison 640
Indexing 642
13.3 MODULES 645
Namespaces, redux 646
13.4 A FLOCKING SIMULATION 648
The World ADT 649
The Boid ADT 655
13.5 A STACK ADT 665
13.6 A DICTIONARY ADT 671
Hash tables 672
Contents  xiii

Implementing a hash table 673


Implementing indexing 676
ADTs vs. data structures 678
13.7 SUMMARY 682
13.8 FURTHER DISCOVERY 682
13.9 PROJECTS 683
Project 13.1 Tracking GPS coordinates 683
Project 13.2 Economic mobility 687
Project 13.3 Slime mold aggregation 690
Project 13.4 Boids in space 692

Appendix A  Installing Python 697


A.1 AN INTEGRATED DISTRIBUTION 697
A.2 MANUAL INSTALLATION 697

Appendix B  Python library reference 701


B.1 MATH MODULE 701
B.2 TURTLE METHODS 702
B.3 SCREEN METHODS 703
B.4 MATPLOTLIB.PYPLOT MODULE 704
B.5 RANDOM MODULE 704
B.6 STRING METHODS 705
B.7 LIST METHODS 706
B.8 IMAGE MODULE 706
B.9 SPECIAL METHODS 707

Bibliography 709

Index 713
This page intentionally left blank
Preface

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


I three 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, who
increasingly benefit from an introduction to computational thinking, beyond the
limited “black box” recipes often found in manuals. 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 solv-
ing 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 prac-
tice 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 ten years has been a revelation; introductory
computer science has become fun again.

xv
xvi  Preface

Web resources
The text, exercises, and projects often refer to files on the book’s accompanying
web site, which can be found at

http://discoverCS.denison.edu .

This web site also includes pointers for further exploration, links to additional
documentation, and errata.

To students
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.
There are many opportunities to delve into topics more deeply. Boxes scattered
throughout the text briefly introduce related, but more technical, 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 “Further discovery” section of each
chapter, you can find additional pointers to explore chapter topics in more depth.
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. All later chapters
conclude with a selection of more involved interdisciplinary projects that you may
be asked by your instructor to tackle.
The book assumes no prior knowledge of computer science. However, it does
assume a modest comfort with high school algebra and mathematical functions.
Occasionally, trigonometry is mentioned, as is the idea of convergence to a limit,
but these are not crucial to an understanding of the main topics in this book.

To instructors
This book may be appropriate for a traditional CS1 course for majors, a CS0 course
for non-majors (at a slower pace and omitting more material), or an introductory
computing course for students in the natural and/or social sciences.
As suggested above, I emphasize computer science principles and the role of
abstraction, both functional and data, throughout the book. I motivate functions
as implementations of functional abstractions, and point out that strings, lists,
and dictionaries are all abstract data types that allow us to solve more interesting
problems than would otherwise be possible. I introduce the idea of time complexity
Preface  xvii

Chapter 1 Chapter 2 Chapter 3


Chapter 4
What is Elementary Visualizing
Growth and decay
computation? computations abstraction

Chapter 7 Chapter 6
Chapter 8 Chapter 5
Designing Text, documents,
Data analysis Forks in the road
programs and DNA

Chapter 10
Chapter 9 Chapter 11
Self-similarity and
Flatland Organizing data
recursion

Chapter 13
Chapter 12
Abstract data
Networks
types

Figure 1 An overview of chapter dependencies.

intuitively, without formal definitions, in the first chapter and return to it several
times as more sophisticated algorithms are developed. The book uses a spiral
approach for many topics, returning to them repeatedly in increasingly complex
contexts. Where appropriate, I also weave into the book topics that are traditionally
left for later computer science courses. A few of these are presented in boxes that
may be covered at your discretion. None of these topics is introduced rigorously, as
they would be in a data structures course. Rather, I introduce them informally and
intuitively to give students a sense of the problems and techniques used in computer
science. I hope that the tables below will help you navigate the book, and see where
particular topics are covered.
This book contains over 600 end-of-section exercises and over 300 in-text reflection
questions that may be assigned as homework or discussed in class. At the end of
most chapters is a selection of projects (about 30 in all) 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.
Because this book is intended for a student who may take additional courses in
computer science and learn other programming languages, I intentionally omit some
features of Python that are not commonly found elsewhere (e.g., simultaneous swap,
chained comparisons, enumerate in for loops). You may, of course, supplement
with these additional syntactical features.
There is more in this book than can be covered in a single semester, giving an
instructor the opportunity to tailor the content to his or her particular situation and
interests. Generally speaking, as illustrated in Figure 1, Chapters 1–6 and 8 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 7, 10, 11, and 13. Chapter 7 contains
xviii  Preface

additional material on program design, including design by contract, assertions and


unit testing that may be skipped without consequences for later chapters. Chapters
9–13 are, more or less, independent of each other. Sections marked with an asterisk
are optional, in the sense that they are not assumed for future sections in that
chapter. When 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 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. The first column lists a selection of representative problems
that are used to motivate the material. The second column lists computer science
principles that are introduced in that chapter. Finally, the third column lists Python
programming topics that are either introduced or reinforced in that chapter to
implement the principles and/or solve the problems.

Chaper 1. What is computation?


Sample problems Principles Programming
• digital music • problems, input/output —
• search engines • abstraction
• GPS devices • algorithms and programs
• smoothing data • computer architecture
• phone trees • binary representations
• time complexity
• Turing machine

Chapter 2. Elementary computations


Sample problems Principles Programming
• wind chill • finite precision • int and float numeric types
• geometry • names as references • arithmetic and the math module
• compounding • using functional • variable names and assignment
interest abstractions • calling built-in functions
• Mad Libs • binary addition • using strings, + and * operators
• print and input

Chapter 3. Visualizing abstraction


Sample problems Principles Programming
• visualizing an • using abstract data types • using classes and objects
archaeological dig • creating functional • turtle module
• random walks abstractions • basic for loops
• ideal gas • basic functional • writing functions
• groundwater flow decomposition • namespaces
• demand functions • docstrings and comments
Preface  xix

Chapter 4. Growth and decay


Sample problems Principles Programming
• network value • accumulators • for loops
• demand and profit • list accumulators • format strings
• loans and investing • difference equations • range
• bacterial growth • approximating continuous • matplotlib
• radiocarbon dating models • appending to lists
• diffusion models • accuracy vs. time • while loops
– SIR, SIS, Bass • error propagation
• competition models • numerical approximation
– Nicholson-Bailey • classes of growth
– Lotka-Volterra
– indirect

Chapter 5. Forks in the road


Sample problems Principles Programming
• random walks • Monte Carlo simulation • random module
• guessing games • pseudorandom number • if/elif/else
• polling and generators • comparison operators
sampling • simulating probabilities • Boolean operators
• particle escape • flag variables • matplotlib histograms
• using uniform and normal • while loops
distributions
• DeMorgan’s laws

Chapter 6. Text, documents, and DNA


Sample problems Principles Programming
• word count • ASCII, Unicode • str class and methods
• textual analysis • linear-time algorithms • iterating over strings
• parsing XML • asymptotic time complexity • indexing and slices
• checksums • linear search • iterating over indices
• concordances • dot plots • reading and writing text files
• detecting plagiarism • string accumulators • nested loops
• congressional votes
• genomics

Chapter 7. Designing programs


Sample problems Principles Programming
• word frequency • problem solving • assert statement
analysis • top-down design • conditional execution
• pre and postconditions of main
• assertions • writing modules
• unit testing
xx  Preface

Chapter 8. Data analysis


Sample problems Principles Programming
• 100-year floods • histograms • list class
• traveling salesman • hash tables • iterating over lists
• Mohs scale • tabular data files • indexing and slicing
• meteorite sites • efficient algorithms • list operators and methods
• zebra migration • linear regression • lists in memory; mutability
• tumor diagnosis • k-means clustering • list parameters
• education levels • heuristics • tuples
• supply and demand • list comprehensions
• voting methods • dictionaries

Chapter 9. Flatland
Sample problems Principles Programming
• earthquake data • 2-D data • 2-D data in list 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

Chapter 10. Self-similarity and recursion


Sample problems Principles Programming
• fractals • self-similarity • writing recursive functions
• cracking passwords • recursion
• Tower of Hanoi • linear search
• maximizing profit • recurrence relations
• path through a maze • divide and conquer
• Lindenmayer system • depth-first search
• electoral districting • grammars
• percolation

Chapter 11. Organizing data


Sample problems Principles Programming
• spell check • binary search • nested loops
• querying data sets • recurrence relations • writing recursive functions
• basic sorting algorithms
• quadratic-time algorithms
• parallel lists
• merge sort
• intractability
• P=NP (intuition)
• Moore’s law
• binary search trees
Preface  xxi

Chapter 12. Networks


Sample problems Principles Programming
• Facebook, Twitter, • graphs • dictionaries
web graphs • adjacency list
• diffusion of ideas • adjacency matrix
• epidemics • breadth-first search
• Oracle of Bacon • distance and shortest paths
• depth-first search
• small-world networks
• scale-free networks
• clustering coefficient
• uniform random graphs

Chapter 13. Abstract data types


Sample problems Principles Programming
• data sets • abstract data types • writing classes
• genomic sequences • data structures • special methods
• rational numbers • stacks • overriding operators
• flocking behavior • hash tables • modules
• slime mold • agent-based simulation
aggregation • swarm intelligence

Software assumptions
To follow along in this book and complete the exercises, you will need to have installed
Python 3.4 (or later) on your computer, and have access to IDLE or another
programming environment. The book also assumes that you have installed the
matplotlib and numpy modules. Please refer to Appendix A for more information.

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 web site. If
you find an error in the text or have another suggestion, please let me know at
havill@denison.edu.
This page intentionally left blank
Acknowledgments

was extraordinarily naı̈ve when I embarked on this project two years ago. “How
I hard can it be to put these ideas into print?” Well, much harder than I thought,
as it turns out. I owe debts of gratitude to many who saw me through to the end.
First and foremost, my family not only tolerated me during this period, but
offered extraordinary support and encouragement. Thank you Beth, for your patience
and strength, and all of the time you have made available to me to work on the
book. I am grateful to my in-laws, Roger and Nancy Vincent, who offered me their
place in Wyoming for a month-long retreat in the final stretch. And, to my four
children, Nick, Amelia, Caroline, and Lillian, I promise to make up for lost time.
My colleagues Matt Kretchmar, Ashwin Lall, and David White used drafts in
their classes, and provided invaluable feedback. They have been fantastic sounding
boards, and have graciously provided many ideas for exercises and projects. Students
in Denison University’s CS 111 and 112 classes caught many typos, especially Gabe
Schenker, Christopher Castillo, Christine Schmittgen, Alivia Tacheny, Emily Lamm,
and Ryan Liedke. Dana Myers read much of the book and offered an abundance of
detailed suggestions. Joan Krone also read early chapters and offered constructive
feedback. I am grateful to Todd Feil for his support, and his frank advice after
reading the almost-final manuscript.
I have benefitted tremendously from many conversations about computational
science, geology, and life with my friend and colleague David Goodwin. Project 8.1
is based on an assignment that he has used in his classes. I have also learned a great
deal from collaborations with Jeff Thompson. Jeff also advised me on Section 6.7
and Project 6.2. Frank Hassebrock enthusiastically introduced me to theories of
problem solving in cognitive psychology. And Dee Ghiloni, the renowned cat herder,
has supported me and my work in more ways than I can count.
I am indebted to the following reviewers, who read early chapters and offered
expert critiques: Terry Andres (University of Manitoba), John Impagliazzo (Qatar
University), Daniel Kaplan (Macalester College), Nathaniel Kell (Duke University),
Andrew McGettrick (University of Strathclyde); Hamid Mokhtarzadeh (University
of Minnesota), George Novacky (University of Pittsburgh), and J. F. Nystrom (Ferris
State University).
I could not have completed this book without the Robert C. Good Fellowship
awarded to me by Denison University.
Finally, thank you to Randi Cohen, for believing in this project, and for her
advice and patience throughout.

xxiii
This page intentionally left blank
About the author

Jessen Havill is a Professor of Computer Science and the Benjamin Barney Chair
of Mathematics at Denison University, where he has been on the faculty since 1998.
Dr. Havill teaches courses across the computer science curriculum, as well as an
interdisciplinary elective in computational biology. He was awarded the college’s
highest teaching honor, the Charles A. Brickman Teaching Excellence Award, in
2013.
Dr. Havill is also an active researcher, with a primary interest in the development
and analysis of online algorithms. In addition, he has collaborated with colleagues
in biology and geosciences to develop computational tools to support research
and teaching in those fields. 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
This page intentionally left blank
CHAPTER 1

What is computation?

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

Michael R. Fellows and Ian Parberry


Computing Research News (1993)

omputers are the most powerful tools ever invented, but not because of their
C versatility and speed, per se. Computers are powerful because they empower
us to innovate and make unprecedented discoveries.
A computer is a machine that carries out a computation, a sequence of simple
steps that transforms some initial information, an input, into some desired result,
the output. Computer scientists harness the power of computers to solve complex
problems by designing solutions that can be expressed as computations. The output
of a computation might be a more efficient route for a spacecraft, a more effective
protocol to control an epidemic, or a secret message hidden in a digital photograph.
Computer science has always been interdisciplinary, as computational problems
arise in virtually every domain imaginable. Social scientists use computational models
to better understand social networks, epidemics, population dynamics, markets,
and auctions. Scholars working in the digital humanities use computational tools to
curate and analyze classic literature. Artists are increasingly incorporating digital
technologies into their compositions and performances. Computational scientists
work in areas related to climate prediction, genomics, particle physics, neuroscience,
and drug discovery.
In this book, we will explore the fundamental problem solving techniques of
computer science, and discover how they can be used to model and solve a variety of
interdisciplinary problems. In this first chapter, we will provide an orientation and
lay out the context in which to place the rest of the book. We will further develop
all of these ideas throughout, so don’t worry if they are not all crystal clear at first.

1
2  What is computation?

mp3 music player

music recording sound

search engine
search terms
search results

Buxton Inn
313 E Broadway GPS device
Granville, OH 43023

address directions

Figure 1.1 Some examples of computational problems.

1.1 PROBLEMS AND ABSTRACTION


Every useful computation solves a problem of some sort. A problem is fundamentally
defined by the relationship between its input and its output, as illustrated in Fig-
ure 1.1. For each problem, we have an input entering on the left and a corresponding
output exiting on the right. In between, a computation transforms the input into a
correct output. When you listen to a song, the music player performs a computation
to convert the digital music file (input) into a sound pattern (output). When you
submit a web search request (input), your computer, and many others across the
Internet, perform computations to get you results (outputs). And when you use GPS
navigation, a device computes directions (output) based on your current position,
your destination, and its stored maps (inputs).
Inputs and outputs are probably also familiar to you from high school algebra.
When you were given an expression like

y = 18x + 31

or
f (x) = 18x + 31,
you may have thought about the variable x as a representation of the input and
y, or f (x), as a representation of the output. In this example, when the input is
x = 2, the output is y = 67, or f (x) = 67. The arithmetic that turns x into y is a
very simple (and boring) example of a computation.

Reflection 1.1 What kinds of problems are you interested in? What are their inputs
and outputs? Are the inputs and outputs, as you have defined them, sufficient to
define the problem completely?
Problems and abstraction  3

To use the technologies illustrated in Figure 1.1 you do not need to understand how
the underlying computation transforms the input to the output; we can think of
the computation as a “black box” and still use the technology effectively. We call
this idea functional abstraction, a very important concept that we often take for
granted. Put simply,
A functional abstraction describes how to use a tool or technology without
necessarily providing any knowledge about how it works.
We exist in a world of abstractions; we could not function without them. We
even think about our own bodies in terms of abstractions. Move your fingers. Did
you need to understand how your brain triggered your nervous and musculoskeletal
systems to make that happen? As far as most of us are concerned, a car is also an
abstraction. To drive a car, do you need to know how turning the steering wheel
turns the car or pushing the accelerator makes it go faster? We understand what
should happen when we do these things, but not necessarily how they happen.
Without abstractions, we would be paralyzed by an avalanche of minutiae.

Reflection 1.2 Imagine that it was necessary to understand how a GPS device
works in order to use it. Or a music player. Or a computer. How would this affect
your ability to use these technologies?

New technologies and automation have introduced new functional abstractions into
everyday life. Our food supply is a compelling example of this. Only a few hundred
years ago, our ancestors knew exactly where their food came from. Inputs of hard
work and suitable weather produced outputs of grain and livestock to sustain a
family. In modern times, we input money and get packaged food; the origins of our
food have become much more abstract.

Reflection 1.3 Think about a common functional abstraction that you use regularly,
such as your phone or a credit card. How has this functional abstraction changed
over time? Can you think of instances in which better functional abstractions have
enhanced our ability to use a technology?

We also use layers of functional abstractions to work more efficiently. For example,
suppose you are the president of a large organization (like a university) that is
composed of six divisions and 5,000 employees. Because you cannot effectively
manage every detail of such a large organization, you assign a vice president to
oversee each of the divisions. You expect each VP to keep you informed about the
general activity and performance of that division, but insulate you from the day-to-
day details. In this arrangement, each division becomes a functional abstraction to
you: you know what each division does, but not necessarily how it does it. Benefitting
from these abstractions, you are now free to focus your resources on more important
organization-level activity. Each VP may utilize a similar arrangement within his
or her division. Indeed, organizations are often subdivided many times until the
number of employees in a unit is small enough to be overseen by a single manager.
4  What is computation?

Computers are similarly built from many layers of functional abstractions. When
you use a computer, you are presented with a “desktop” abstraction on which you
can store files and use applications (i.e., programs) to do work. That there appear
to be many applications executing simultaneously is also an abstraction. In reality,
some applications may be executing in parallel while others are being executed
one at a time, but alternating so quickly that they just appear to be executing in
parallel. This interface and the basic management of all of the computer’s resources
(e.g., hard drives, network, memory, security) is handled by the operating system.
An operating system is a complicated beast that is often mistakenly described as
“the program that is always running in the background on a computer.” In reality,
the core of an operating system provides several layers of functional abstractions
that allow us to use computers more efficiently.
Computer scientists invent computational processes (e.g., search engines, GPS
software, and operating systems), that are then packaged as functional abstractions
for others to use. But, as we will see, they also harness abstraction to correctly
and efficiently solve real-world problems. These problems are usually complicated
enough that they must be decomposed into smaller problems that human beings can
understand and solve. Once solved, each of these smaller pieces becomes a functional
abstraction that can be used in the solution to the original problem.
The ability to think in abstract terms also enables us to see similarities in prob-
lems from different domains. For example, by isolating the fundamental operations
of sexual reproduction (i.e., mutation and recombination) and natural selection (i.e.,
survival of the fittest), the process of evolution can be thought of as a randomized
computation. From this insight was borne a technique called evolutionary computa-
tion that has been used to successfully solve thousands of problems. Similarly, a
technique known as simulated annealing applies insights gained from the process
of slow-cooling metals to effectively find solutions to very hard problems. Other
examples include techniques based on the behaviors of crowds and insect swarms,
the operations of cellular membranes, and how networks of neurons make decisions.

1.2 ALGORITHMS AND PROGRAMS


Every useful computation follows a sequence of steps to transform an input into a
correct output. This sequence of steps is called an algorithm. To illustrate, let’s look
at a very simple problem: computing the volume of a sphere. In this case, the input
is the radius r of the sphere and the output is the volume of the sphere with radius
r. To compute the output from the input, we simply use the well-known formula
V = (4/3)πr3 . This can be visualized as follows.

radius r (4/3) π r3 volume of sphere with radius r

In the box is a representation of the algorithm: multiply 4/3 by π by the radius


cubed, and output the result. However, the formula is not quite the same as an
algorithm because there are several alternative sequences of steps that one could
Algorithms and programs  5

use to carry out this formula. For example, each of these algorithms computes the
volume of a sphere.

1. Divide 4 by 3. 1. Compute r × r × r.
2. Multiply the previous result by π. 2. Multiply the previous result by π.
or
3. Repeat the following three times: 3. Multiply the previous result by 4.
multiply the previous result by r. 4. Divide the previous result by 3.

Both of these algorithms use the same formula, but they execute the steps in
different ways. This distinction may seem trivial to us but, depending on the level
of abstraction, we may need to be this explicit when “talking to” a computer.

Reflection 1.4 Write yet another algorithm that follows the volume formula.

To execute an algorithm on a computer as a computation, we need to express the


algorithm in a language that the computer can “understand.” These computer
languages are called programming languages, and an implementation of an algorithm
in a programming language is called a program. Partial or whole programs are often
called source code, or just code, which is why computer programming is also known
as coding. Packaged programs, like the ones you see on your computer desktop, are
also called applications or apps, and are collectively called software (as opposed to
hardware, which refers to physical computer equipment).
There are many different programming languages in use, each with its own
strengths and weaknesses. In this book, we will use a programming language called
Python. To give you a sense of what is to come, here is a Python program that
implements the sphere-volume algorithm:

def sphereVolume(radius):
volume = (4 / 3) * 3.14159 * (radius ** 3)
return volume

result = sphereVolume(10)
print(result)

Each line in a program is called a statement. The first statement in this program,
beginning with def, defines a new function. Like an algorithm, a function contains a
sequence of steps that transforms an input into an output. In this case, the function is
named sphereVolume, and it takes a single input named radius, in the parentheses
following the function name. The second line, which is indented to indicate that it is
part of the sphereVolume function, uses the volume formula to compute the volume
of the sphere, and then assigns this value to a variable named volume. The third line
indicates that the value assigned to volume should be “returned” as the function’s
output. These first three lines only define what the sphereVolume function should
do; the fourth line actually invokes the sphereVolume function with input radius
6  What is computation?

problem

solve

algorithm

implement

high-level program

execute or “run”

computation

Figure 1.2 The layers of functional abstraction in a computation.

equal to 10, and assigns the result (41.88787) to the variable named result. The
fifth line, you guessed it, prints the value assigned to result.
If you have never seen a computer program before, this probably looks like
“Greek” to you. But, at some point in your life, so did (4/3)πr3 . (What is this
symbol π? How can you do arithmetic with a letter? What is that small 3 doing
up there? There is no “plus” or “times” symbol; is this even math?) The same
can be said for notations like H2 O or 19○ C. But now that you are comfortable
with these representations, you can appreciate that they are more convenient and
less ambiguous than representations like “multiply 4/3 by π by the radius cubed”
and “two atoms of hydrogen and one atom of oxygen.” You should think of a
programming language as simply an extension of the familiar arithmetic notation.
But programming languages enable us to express algorithms for problems that reach
well beyond simple arithmetic.
The process that we have described thus far is illustrated in Figure 1.2. We start
with a problem having well-defined input and output. We then solve the problem
by designing an algorithm. Next, we implement the algorithm by expressing it as
a program in a programming language. Programming languages like Python are
often called high-level because they use familiar words like “return” and “print,”
and enable a level of abstraction that is familiar to human problem solvers. (As we
will see in Section 1.4, computers do not really “understand” high-level language
programs.) Finally, executing the program on a computer initiates the computation
Algorithms and programs  7

that gives us our results. (Executing a program is also called “running” it.) As we
will see soon, this picture is hiding some details, but it is sufficient for now.
Let’s look at another, slightly more complicated problem. Suppose, as part of an
ongoing climate study, we are tracking daily maximum water temperatures recorded
by a drifting buoy in the Atlantic Ocean. We would like to compute the average (or
mean) of these temperatures over one year. Suppose our list of high temperature
readings (in degrees Celsius) starts like this:
18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 19.1, 19.4, 19.3, ...

Reflection 1.5 What are the input and output for this problem? Think carefully
about all the information you need in the input. Express your output in terms of the
input.

The input to the mean temperature problem obviously includes the list of tempera-
tures. We also need to know how many temperatures we have, since we need to divide
by that number. The output is the mean temperature of the list of temperatures.

Reflection 1.6 What algorithm can we use to find the mean daily temperature?
Think in terms of the steps we followed in the algorithms to compute the volume of
a sphere.

Of course, we know that we need to add up all the temperatures and divide by the
number of days. But even a direction as simple as “add up all the temperatures” is too
complex for a computer to execute directly. As we will see in Section 1.4, computers
are, at their core, only able to execute instructions on par with simple arithmetic
on two numbers at a time. Any complexity or “intelligence” that we attribute to
computers is actually attributable to human beings harnessing this simple palette of
instructions in creative ways. Indeed, this example raises two necessary characteristics
of computer algorithms: their steps must be both unambiguous and executable by a
computer. In other words, the steps that a computer algorithm follows must correlate
to things a computer can actually do, without inviting creative interpretation by a
human being.

An algorithm is a sequence of unambiguous, executable statements that


solves a problem by transforming an input into a correct output.

These two requirements are not really unique to computer algorithms. For example,
we hope that new surgical techniques are unambiguously presented and reference
actual anatomy and real surgical tools. Likewise, when an architect designs a
building, she must take into account the materials available and be precise about
their placement. And when an author writes a novel, he must write to his audience,
using appropriate language and culturally familiar references.
To get a handle on how to translate “add up all the temperatures” into something
a computer can understand, let’s think about how we would do this without a
8  What is computation?

calculator or computer: add two numbers at a time to a running sum. First, we


initialize our running sum to 0. Then we add the first temperature value to the
running sum: 0 + 18.9 = 18.9. Then we add the second temperature value to this
running sum: 18.9+18.9 = 37.8. Then we add the third temperature: 37.8+19.0 = 56.8.
And we continue like this until we have added all the temperatures. Suppose our
final sum is 8,696.8 and we have summed over 365 days (for a non-leap year). Then
we can compute our final average by dividing the sum by the number of days:
8, 696.8/365 ≈ 23.8. A step-by-step sequence of instructions for this algorithm might
look like the following:

Algorithm Mean Temperature


Input: a list of 365 daily temperatures
1. Initialize the running sum to 0.
2. Add the first temperature to the running sum, and assign the result
to be the new running sum.
3. Add the second temperature to the running sum, and assign the result
to be the new running sum.
4. Add the third temperature to the running sum, and assign the result
to be the new running sum.

366. Add the 365th temperature to the running sum, and assign the result
to be the new running sum.
367. Divide the running sum by the number of days, 365, and assign the
result to be the mean temperature.
Output: the mean temperature

Since this 367-step algorithm is pretty cumbersome to write, and steps 2–366 are
essentially the same, we can shorten the description of the algorithm by substituting
steps 2–366 with
For each temperature t in our list, repeat the following:

add t to the running sum, and assign the result to be the new
running sum.

In this shortened representation, which is called a loop, t stands in for each temper-
ature. First, t is assigned the first temperature in the list, 18.9, which the indented
statement adds to the running sum. Then t is assigned the second temperature, 18.9,
which the indented statement next adds to the running sum. Then t is assigned the
third temperature, 19.0. And so on. With this substitution (in red), our algorithm
becomes:
Algorithms and programs  9

Algorithm Mean Temperature 2


Input: a list of 365 daily temperatures
1. Initialize the running sum to 0.
2. For each temperature t in our list, repeat the following:
add t to the running sum, and assign the result to be the new
running sum.
3. Divide the running sum by the number of days, 365, and assign the
result to be the mean temperature.
Output: the mean temperature

We can visualize the execution of this loop more explicitly by “unrolling” it into its
equivalent sequence of statements. The statement indented under step 2 is executed
once for each different value of t in the list. Each time, the running sum is updated.
So, if our list of temperatures is the same as before, this loop is equivalent to the
following sequence of statements:

(a) Add 18.9 to 0 , and assign 18.9 to be the new running sum.
± ® ±
t the running sum the result

(b) Add 18.9 to 18.9 , and assign 37.8 to be the new running sum.
± ± ±
t the running sum the result

(c) Add 19.0 to 37.8 , and assign 56.8 to be the new running sum.
± ± ±
t the running sum the result

Another important benefit of the loop representation is that it renders the algorithm
representation independent of the length of the list of temperatures. In Mean Tem-
perature 1, we had to know up front how many temperatures there were because
we needed one statement for each temperature. However, in Mean Temperature
2, there is no mention of 365, except in the final statement; the loop simply repeats
as long as there are temperatures remaining. Therefore, we can generalize Mean
Temperature 2 to handle any number of temperatures. Actually, there is nothing
in the algorithm that depends on these values being temperatures at all, so we
should also generalize it to handle any list of numbers. If we let n denote the length
of the list, then our generalized algorithm looks like the following:
10  What is computation?

Algorithm Mean
Input: a list of n numbers
1. Initialize the running sum to 0.
2. For each number t in our list, repeat the following:
Add t to the running sum, and assign the result to be the new
running sum.
3. Divide the running sum by n, and assign the result to be the mean.
Output: the mean

As you can see, there are often different, but equivalent, ways to represent an
algorithm. Sometimes the one you choose depends on personal taste and the pro-
gramming language in which you will eventually express it. Just to give you a sense
of what is to come, we can express the Mean algorithm in Python like this:
def mean(values):
n = len(values)
sum = 0
for number in values:
sum = sum + number
mean = sum / n
return mean

Try to match the statements in Mean to the statements in the program. By doing
so, you can get a sense of what each part of the program must do. We will flesh
this out in more detail later, of course; in a few chapters, programs like this will
be second nature. As we pointed out earlier, once you are comfortable with this
notation, you will likely find it much less cumbersome and more clear than writing
everything in full sentences, with the inherent ambiguities that tend to emerge in
the English language.

Exercises
1.2.1. Describe three examples from your everyday life in which an abstraction is beneficial.
Explain the benefits of each abstraction versus what life would be like without it.
1.2.2. Write an algorithm to find the minimum value in a list of numbers. Like the
Mean algorithm, you may only examine one number at a time. But instead of
remembering the current running sum, remember the current minimum value.
1.2.3. You are organizing a birthday party where cookies will be served. On the invite
list are some younger children and some older children. The invite list is given in
shorthand as a list of letters, y for a young child and o for an older child. Each
older child will eat three cookies, while each younger child will eat two cookies.
Efficient algorithms  11

Write an algorithm that traces through the list, and prints how many cookies are
needed. For example, if the input were y, y, o, y, o then the output should be 12
cookies.
1.2.4. Write an algorithm for each player to follow in a simple card game like Blackjack
or Go Fish. Assume that the cards are dealt in some random order.
1.2.5. Write an algorithm to sort a stack of any 5 cards by value in ascending order. In
each step, your algorithm may compare or swap the positions of any two cards.
1.2.6. Write an algorithm to walk between two nearby locations, assuming the only legal
instructions are “Take s steps forward,” and “Turn d degrees to the left,” where s
and d are positive integers.

1.3 EFFICIENT ALGORITHMS


For any problem, there may be many possible algorithms that correctly solve it.
However, not every algorithm is equally good. We will illustrate this point with two
problems: organizing a phone tree and “smoothing” data from a “noisy” source.

Organizing a phone tree


Imagine that you have been asked to organize an old-fashioned “phone tree” for
your organization to personally alert everyone with a phone call in the event of
an emergency. You have to make the first call, but after that, you can delegate
others to make calls as well. Who makes which calls and the order in which they are
made constitutes an algorithm. For example, suppose there are only eight people
in the organization, and they are named Amelia, Beth, Caroline, Dave, Ernie, Flo,
Gretchen, and Homer. Then here is a simple algorithm:

Algorithm Alphabetical Phone Tree


1. Amelia calls Beth.
2. Beth calls Caroline.
3. Caroline calls Dave.

7. Gretchen calls Homer.

(For simplicity, we will assume that everyone answers the phone right away and
every phone call takes the same amount of time.) Is this the best algorithm for
solving the problem? What does “best” even mean?

Reflection 1.7 For the “phone tree” problem, what characteristics would make one
algorithm better than another?

As the question suggests, deciding whether one algorithm is better than another
12  What is computation?

(a) A 1 B 2 C 3 D 4 E 5 F 6 G 7 H

A
(b)
4
3 5
2 6
1 7
B C D E F G H

1 2

(c) B C

2 3 3 4

D E F G
3

Illustrations of three possible phone tree algorithms. Each name is repre-


Figure 1.3
sented by its first letter, calls are represented by arrows, and the numbers indicate
the order in which the calls are made.

depends on your criteria. For the “phone tree” problem, your primary criterion may
be to make as few calls as possible yourself, delegating most of the work to others.
The Alphabetical Phone Tree algorithm, graphically depicted in Figure 1.3(a),
is one way to satisfy this criterion. Alternatively, you may feel guilty about making
others do any work, so you decide to make all the calls yourself; this is depicted
in Figure 1.3(b). However, in the interest of community safety, we should really
organize the phone tree so that the last person is notified of the emergency as soon
as possible. Both of the previous two algorithms fail miserably in this regard. In fact,
they both take the longest possible time! A better algorithm would have you call
two people, then each of those people call two people, and so on. This is depicted in
Figure 1.3(c). Notice that this algorithm notifies everyone in only four steps because
more than one phone call happens concurrently; A and B are both making calls
during the second step; and B, C, and D are all making calls in the third step.
If all of the calls were utilizing a shared resource (such as a wireless network),
we might need to balance the time with the number of simultaneous calls. This
may not seem like an issue with only eight people in our phone tree, but it would
become a significant issue with many more people. For example, applying the
algorithm depicted in Figure 1.3(c) to thousands of people would result in thousands
of simultaneous calls.
Let’s now consider how these concerns might apply to algorithms more generally.
Efficient algorithms  13

(a) (b)
Plot of (a) a year’s worth of daily high temperature readings and (b) the
Figure 1.4
temperature readings smoothed over a five-day window.

Reflection 1.8 What general characteristics might make one algorithm for a par-
ticular problem better than another algorithm for the same problem?

As was the case in the phone tree problem, the most important hallmark of a good
algorithm is speed; given the choice, we almost always want the algorithm that
requires the least amount of time to finish. (Would you rather wait five minutes
for a web search or half of a second?) But there are other attributes as well that
can distinguish one algorithm from another. For example, we saw in Section 1.2
how a long, tedious algorithm can be represented more compactly using a loop;
the more compact version is easier to write down and translate into a program.
The compact version also requires less space in a computer’s memory. Because the
amount of storage space in a computer is limited, we want to create algorithms that
use as little of this resource as possible to store both their instructions and their
data. Efficient resource usage may also apply to network capacity, as in the phone
tree problem on a wireless network. In addition, just as writers and designers strive
to create elegant works, computer scientists pride themselves on writing elegant
algorithms that are easy to understand and do not contain extraneous steps. And
some advanced algorithms are considered to be especially important because they
introduce new techniques that can be applied to solve other hard problems.

A smoothing algorithm
To more formally illustrate how we can evaluate the time required by an algorithm,
let’s revisit the sequence of temperature readings from the previous section. Often,
when we are dealing with large data sets (much longer than this), anomalies can
arise due to errors in the sensing equipment, human fallibility, or in the network used
to send results to a lab or another collection point. We can mask these erroneous
measurements by “smoothing” the data, replacing each value with the mean of
the values in a “window” of values containing it. This technique is also useful for
14  What is computation?

(a) (b)
Figure 1.5Plot of (a) the ten high temperature readings and (b) the temperature
readings smoothed over a five-day window.

extracting general patterns in data by eliminating distracting “bumpy” areas. For


example, Figure 1.4 shows a year’s worth of raw temperature data from a floating
ocean buoy, next to the same data smoothed over a five day window.
Let’s design an algorithm for this problem. To get a better sense of the problem
and the technique we will use, we will begin by looking at a small example consisting
of the first ten temperature readings from the previous section, with an anomalous
reading inserted. Specifically, we will replace the 19.1○ C reading in the eighth
position with an erroneous temperature of 22.1○ C:

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3

The plot of this data in Figure 1.5(a) illustrates this erroneous “bump.”
Now let’s smooth the data by averaging over windows of size five. For each value
in the original list, its window will include itself and the four values that come
before it. Our algorithm will need to compute the mean of each of these windows,
and then add each of these means to a new smoothed list. The last four values do
not have four more values after them, so our smoothed list will contain four fewer
values than our original list. The first window looks like this:

18.9, 18.9, 19.0, 19.2, 19.3 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 95.3 / 5 = 19.06

To find the mean temperature for the window, we sum the five values and divide by
5. The result, 19.06, will represent this window in the smoothed list. The remaining
five windows are computed in the same way:

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 95.7 / 5 = 19.14
Efficient algorithms  15

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 96.0 / 5 = 19.20

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 99.1 / 5 = 19.82

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 99.3 / 5 = 19.86

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
mean = 99.3 / 5 = 19.86

In the end, our list of smoothed temperature readings is:

19.06, 19.14, 19.20, 19.82, 19.86, 19.86

We can see from the plot of this smoothed list in Figure 1.5(b) that the “bump” has
indeed been smoothed somewhat.
We can express our smoothing algorithm using notation similar to our previous
algorithms. Notice that, to find each of the window means in our smoothing algorithm,
we call upon our Mean algorithm from Section 1.2.

Algorithm Smooth
Input: a list of n numbers and a window size w
1. Create an empty list of mean values.
2. For each position d, from 1 to n − w + 1, repeat the following:
(a) invoke the Mean algorithm on the list of numbers between
positions d and d + w − 1;
(b) append the result to the list of mean values.
Output: the list of mean values

Step 1 creates an empty list to hold the window means. We will append the mean
for each window to the end of this list after we compute it. Step 2 uses a loop to
compute the means for all of the windows. This loop is similar to the loop in the
Mean algorithm: the variable d takes on the values between 1 and n − w + 1, like t
took on each value in the list in the Mean algorithm. First, d is assigned the value
1, and the mean of the window between positions 1 and 1 + w − 1 = w is added to
the list of mean values. Then d is assigned the value 2, and the mean of the window
between positions 2 and 2 + w − 1 = w + 1 is added to the list of mean values. And so
on, until d takes on the value of n − w + 1, and the mean of the window between
positions n − w + 1 and (n − w + 1) + w − 1 = n is added to the list of mean values.
16  What is computation?

Reflection 1.9 Carry out each step of the Smooth algorithm with w = 5 and the
ten-element list in our example:

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3

Compare each step with what we worked out above to convince yourself that the
algorithm is correct.

How long does it take?


To determine how much time this algorithm requires to smooth the values in a
list, we could implement it as a program and execute it on a computer. However,
this approach presents some problems. First, which list(s) do we use for our timing
experiments? Second, which value(s) of w do we use? Third, which computer(s) do
we use? Will these specific choices give us a complete picture of our algorithm’s
efficiency? Will they allow us to predict the time required to smooth other lists on
other computers? Will these predictions still be valid ten years from now?
A better way to predict the amount of time required by an algorithm is to
count the number of elementary steps that are required. An elementary step is one
that always requires the same amount of time, regardless of the input. By counting
elementary steps, we can estimate how long an algorithm will take on any computer,
relative to another algorithm for the same problem. For example, if algorithm A
requires 100 elementary steps while algorithm B requires 300 elementary steps, we
know that algorithm A will always be about three times faster than algorithm B,
regardless of which computer we run them both on.
Let’s look at which steps in the Smooth algorithm qualify as elementary steps.
Step 1 qualifies because creating an empty list makes no reference to the input at
all. But step 2 does not qualify because its duration depends on the values of n
and w, which are both part of the input. Similarly, step 2(a) does not qualify as an
elementary step because its duration depends on the time required by the Mean
algorithm, which depends on the value of w. Finding the mean temperature of the
window between positions 1 and w will take longer when w is 10 than it will when
w is 3. However, each addition and division operation required to compute a mean
does qualify as an elementary step because the time required for an arithmetic
operation is independent of the operands (up to a point). Step 2(b) also qualifies as
an elementary step because, intuitively, adding something to the end of a list should
not depend on how many items are in the list (as long as we have direct access to
the end of the list).

Reflection 1.10 Based on this analysis, what are the elementary steps in this
algorithm? How many times are they each executed?

The only elementary steps we have identified are creating a list, appending to a
list, and arithmetic operations. Let’s start by counting the number of arithmetic
operations that are required. If each window has size five, then we perform five
Efficient algorithms  17

addition operations and one division operation each time we invoke the Mean
algorithm, for a total of six arithmetic operations per window. Therefore, the total
number of arithmetic operations is six times the number of windows. In general, the
window size is denoted w and there are n − w + 1 windows. So the algorithm performs
w additions and one division per window, for a total of (w + 1) ⋅ (n − w + 1) arithmetic
operations. For example, smoothing a list of 365 temperatures with a window size
of five days will require (w + 1) ⋅ (n − w + 1) = 6 ⋅ (365 − 5 + 1) = 2, 166 arithmetic
operations. In addition to the arithmetic operations, we create the list once and
append to the list once for every window, a total of n − w + 1 times. Therefore, the
total number of elementary steps is
(w + 1) ⋅ (n − w + 1) + 1 + n − w + 1 .
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹¸ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹¶ ® ´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹¸¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
arithmetic create appends
list

This expression can be simplified a bit to (w + 2) ⋅ (n − w + 1) + 1.


This number of elementary steps is called an algorithm’s time complexity. An
algorithm’s time complexity is always measured with respect to the size of the
input. In this case, the size of the input depends on n, the length of the list, and w,
the window size. As we will discuss later, we could simplify this unpleasant time
complexity expression by just taking into account the terms that matter when the
input gets large. But, for now, we will leave it as is.
Reflection 1.11 Can you think of a way to solve the smoothing problem with fewer
arithmetic operations?

A better smoothing algorithm


We can design a more efficient smoothing algorithm, one requiring fewer elementary
steps, by exploiting the following simple observation. While finding the sums of
neighboring windows in the Smooth algorithm, we unnecessarily performed some
addition operations more than once. For example, we added the fourth and fifth
temperature readings four different times, once in each of the first four windows.
We can eliminate this extra work by taking advantage of the relationship between
the sums of two contiguous windows. For example, consider the first window:
18.9, 18.9, 19.0, 19.2, 19.3 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
sum = 95.3

The sum for the second window must be almost the same as the first window, since
they have four numbers in common. The only difference in the second window is
that it loses the first 18.9 and gains 19.3. So once we have the sum for the first
window (95.3), we can get the sum of the second window with only two additional
arithmetic operations: 95.3 − 18.9 + 19.3 = 95.7.
18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3
´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
sum = 95.7
18  What is computation?

We can apply this process to every subsequent window as well. At the end of the
algorithm, once we have the sums for all of the windows, we can simply divide each
by its window length to get the final list of means. Written in the same manner as
the previous algorithms, our new smoothing algorithm looks like this:

Algorithm Smooth 2
Input: a list of n numbers and a window size w
1. Create an empty list of window sums.
2. Compute the sum of the first w numbers and
append the result to the list of window sums.
3. For each position d, from 2 to n − w + 1, repeat the following:
(a) subtract the number in position d − 1 from the previous window
sum and then add the number in position d + w − 1;
(b) append the result to the list of window sums.
4. For each position d, from 1 to n − w + 1, repeat the following:
(a) divide the dth window sum by w.
Output: the list of mean values

Step 2 computes the sum for the first window and adds it to a list of window sums.
Step 3 then computes the sum for each subsequent window by subtracting the
number that is lost from the previous window and adding the number that is gained.
Finally, step 4 divides all of the window sums by w to get the list of mean values.

Reflection 1.12 As with the previous algorithm, carry out each step of the Smooth
2 algorithm with w = 5 and the ten-element list in our example:

18.9, 18.9, 19.0, 19.2, 19.3, 19.3, 19.2, 22.1, 19.4, 19.3

Does the Smooth 2 algorithm actually require fewer elementary steps than our
first attempt? Let’s look at each step individually. As before, step 1 counts as one
elementary step. Step 2 requires w − 1 addition operations and one append, for a
total of w elementary steps. Step 3 performs an addition, a subtraction, and an
append for every window but the first, for a total of 3(n − w) elementary steps.
Finally, step 4 performs one division operation per window, for a total of n − w + 1
arithmetic operations. This gives us a total of

1 + w + 3 (n − w) + n − w + 1
® ® ´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¸¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶ ´¹¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹¸¹ ¹ ¹ ¹ ¹ ¹ ¹ ¹ ¶
create first divisions
other
list window windows
Efficient algorithms  19

elementary steps. Combining all of these terms, we find that the time complexity of
Smooth 2 is 4n − 3w + 2. Therefore, our old algorithm requires

(w + 2) ⋅ (n − w + 1) + 1
4n − 3w + 2
times as many operations as the new one. It is hard to tell from this fraction, but
our new algorithm is about w/4 times faster than our old one. To see this, suppose
our list contains n = 10, 000 temperature readings. The following table shows the
value of the fraction for increasing window sizes w.

w Speedup
5 1.7
10 3.0
20 5.5
100 25.4
500 123.9
1,000 243.7

When w is small, our new algorithm does not make much difference, but the difference
becomes quite pronounced when w gets larger. In real applications of smoothing on
extremely large data sets containing billions or trillions of items, window sizes can
be as high as w = 100, 000. For example, smoothing is commonly used to visualize
statistics over DNA sequences that are billions of units long. So our refined algorithm
can have a marked impact! Indeed, as we will examine further in Section 6.4, it is
often the case that a faster algorithm can reduce the time required for a computation
significantly more than faster hardware.

Exercises
1.3.1. The phone tree algorithm depicted in Figure 1.3(c) comes very close to making
all of the phone calls in three steps. Is it possible to actually achieve three steps?
How?
1.3.2. Suppose the phone tree algorithm illustrated in Figure 1.3(c) was being executed
with a large number of people. We saw one call made during the first time step,
two calls during the second time step, and three calls during the third time step.
(a) How many concurrent calls would be made during time steps 4, 5, and 6?
(b) In general, can you provide a formula (or algorithm) to determine the number
of calls made during any time step t?
1.3.3. Describe the most important criterion for evaluating how good an algorithm is.
Then add at least one more criterion and describe how it would be applied to
algorithms for some everyday problem.
1.3.4. What is the time complexity of the Mean algorithm on Page 10, in terms of n
(the size of the input list)?
20  What is computation?

processors memory

core 1
HD / SSD Internet printer

core 2

bus

Figure 1.6 A simplified schematic diagram of a computer.

1.4 COMPUTERS ARE DUMB


By executing clever algorithms very fast, computers can sometimes appear to exhibit
primitive intelligence. In a historic example, in 1997, the IBM Deep Blue computer
defeated reigning world champion Garry Kasparov in a six-game match of chess.
More recently, in 2011, IBM’s Watson computer beat two champions in the television
game show Jeopardy.
The intelligence that we sometimes attribute to computers, however, is actually
human intelligence that was originally expressed as an algorithm, and then as a
program. Even the statements in a high-level programming language are themselves
abstract conveniences built upon a much more rudimentary set of instructions, called
a machine language, that a computer can execute natively.
Every statement in a Python program must be translated into a sequence of
equivalent machine language instructions before it can be executed by a computer.
This process is handled automatically, and somewhat transparently, by either a
program called an interpreter or a program called a compiler . An interpreter
translates one line of a high-level program into machine language, executes it, then
translates the next line and executes it, etc. A compiler instead translates a high-level
language program all at once into machine language. Then the compiled machine
language program can be executed from start to finish without additional translation.
This tends to make compiled programs faster than interpreted ones. However,
interpreted languages allow us to more closely interact with a program during its
execution. As we will see in Chapter 2, Python is an interpreted programming
language.

Inside a computer
The types of instructions that constitute a machine language are based on the internal
design of a modern computer. As illustrated in Figure 1.6, a computer essentially
consists of one or more processors connected to a memory. A computer’s memory,
Computers are dumb  21

often called RAM (short for random access memory), is conceptually organized as
a long sequence of cells, each of which can contain one unit of information. Each
cell is labeled with a unique memory address that allows the processor to reference
it specifically. So a computer’s memory is like a huge sequence of equal-sized post
office boxes, each of which can hold exactly one letter. Each P.O. box number is
analogous to a memory address and a letter is analogous to one unit of information.
The information in each cell can represent either one instruction or one unit of
data.1 So a computer’s memory stores both programs and the data on which the
programs work.
A processor, often called a CPU (short for central processing unit) or a core,
contains both the machinery for executing instructions and a small set of memory
locations called registers that temporarily hold data values needed by the current
instruction. If a computer contains more than one core, as most modern computers
do, then it is able to execute more than one instruction at a time. These instructions
may be from different programs or from the same program. This means that our
definition of an algorithm as a sequence of instructions on Page 7 is not strictly
correct. In fact, an algorithm (or a program) may consist of several semi-independent
sequences of steps called threads that cooperatively solve a problem.
As illustrated in Figure 1.6, the processors and memory are connected by a
communication channel called a bus. When a processor needs a value in memory,
it transmits the request over the bus, and then the memory returns the requested
value the same way. The bus also connects the processors and memory to several
other components that either improve the machine’s efficiency or its convenience,
like the Internet and secondary storage devices like hard drives, solid state drives,
and flash memory. As you probably know, the contents of a computer’s memory are
lost when the computer loses power, so we use secondary storage to preserve data
for longer periods of time. We interact with these devices through a “file system”
abstraction that makes it appear as if our hard drives are really filing cabinets.
When you execute a program or open a file, it is first copied from secondary storage
into memory where the processor can access it.

Machine language
The machine language instructions that a processor can execute are very simple. For
example, consider something as simple as computing x = 2 + 5. In a program, this
statement adds 2 and 5, and stores the result in a memory location referred to by
the variable x. But even this is likely to be too complex for one machine language
instruction. The machine language equivalent likely, depending on the computer,
consists of four instructions. The first instruction loads the value 2 into a register in
the processor. The second instruction loads the value 5 into another register in the
processor. The third instruction adds the values in these two registers, and stores
1
In reality, each instruction or unit of data usually occupies multiple contiguous cells.
22  What is computation?

Box 1.1: High performance computing


Although today’s computers are extremely fast, there are some problems that are so big
that additional power is necessary. These include weather forecasting, molecular modeling
and drug design, aerodynamics, and deciphering encrypted data. For these problems,
scientists use supercomputers. A supercomputer, or high performance computer , is made
of up to tens of thousands of nodes, connected by a very fast data network that shuttles
information between nodes. A node, essentially a standalone computer, can contain
multiple processors, each with multiple cores. The fastest supercomputers today have
millions of cores and a million gigabytes of memory.
To realize the power of these computers, programmers need to supply their cores with a
constant stream of data and instructions. The results computed by the individual cores
are then aggregated into an overall solution. The algorithm design and programming
techniques, known as parallel programming, are beyond the scope of this book, but we
provide additional resources at the end of the chapter if you would like to learn more.

the result in a third register. Finally, the fourth instruction stores the value in the
third register into the memory cell with address x.
From the moment a computer is turned on, its processors are operating in a
continuous loop called the fetch and execute cycle (or machine cycle). In each cycle,
the processor fetches one machine language instruction from memory and executes
it. This cycle repeats until the computer is turned off or loses power. In a nutshell,
this is all a computer does. The rate at which a computer performs the fetch and
execute cycle is loosely determined by the rate at which an internal clock “ticks”
(the processor’s clock rate). The ticks of this clock keep the machine’s operations
synchronized. Modern personal computers have clocks that tick a few billion times
each second; a 3 gigahertz (GHz) processor ticks 3 billion times per second (“giga”
means “billion” and a “hertz” is one tick per second).
So computers, at their most basic level, really are quite dumb; the processor
blindly follows the fetch and execute cycle, dutifully executing whatever sequence
of simple instructions we give it. The frustrating errors that we yell at computers
about are, in fact, human errors. The great thing about computers is not that they
are smart, but that they follow our instructions so very quickly; they can accomplish
an incredible amount of work in a very short amount of time.

Everything is bits
Our discussion so far has glossed over a very important consideration: in what
form does a computer store programs and data? In addition to machine language
instructions, we need to store numbers, documents, maps, images, sounds, presenta-
tions, spreadsheets, and more. Using a different storage medium for each type of
information would be insanely complicated and inefficient. Instead, we need a simple
storage format that can accommodate any type of data. The answer is bits. A bit
Computers are dumb  23

is the simplest possible unit of information, capable of taking on one of only two
values: 0 or 1 (or equivalently, off/on, no/yes, or false/true). This simplicity makes
both storing information (i.e., memory) and computing with it (e.g., processors)
relatively simple and efficient.

Bits are switches


Storing the value of a bit is absurdly simple: a bit is equivalent to an on/off switch,
and the value of the bit is equivalent to the state of the switch: off = 0 and on = 1.
A computer’s memory is essentially composed of billions of microscopic switches,
organized into memory cells. Each memory cell contains 8 switches, so each cell
can store 8 bits, called a byte. We represent a byte simply as a sequence of 8 bits,
such as 01101001. A computer with 8 gigabytes (GB) of memory contains about 8
billion memory cells, each storing one byte. (Similarly, a kilobyte (KB) is about one
thousand bytes, a megabyte (MB) is about one million bytes, and a terabyte (TB)
is about one trillion bytes.)

Bits can store anything


A second advantage of storing information with bits is that, as the simplest possible
unit of information, it serves as a “lowest common denominator”: all other informa-
tion can be converted to bits in fairly straightforward manners. Numbers, words,
images, music, and machine language instructions are all encoded as sequences of
bits before they are stored in memory. Information stored as bits is also said to be
in binary notation. For example, consider the following sequence of 16 bits (or two
bytes).

0100010001010101

This bit sequence can represent each of the following, depending upon how it is
interpreted:

(a) the integer value 17,493;

(b) the decimal value 2.166015625;

(c) the two characters “DU”;

(d) the Intel machine language instruction inc x (inc is short for “increment”);
or

(e) the following 4 × 4 black and white image, called a bitmap (0 represents a
white square and 1 represents a black square).
Other documents randomly have
different content
that they have to endure the same hardships, may, and very often
does, exercise pressure upon the authorities to surrender. Further,
should the commander of a besieged place expel the non-
combatants in order to lessen the number of those who consume his
store of provisions, the besieging force need not allow them to pass
through its lines, but may drive them back.[302]
[300] See above, § 110.
[301] Thus in 1870, during the Franco-German War, the German besiegers of Strassburg
as well as of Belfort allowed the women, the children, and the sick to leave the besieged
fortresses.
[302] See Land Warfare, § 129.

That diplomatic envoys of neutral Powers may not be prevented


from leaving a besieged town is a consequence of their
exterritoriality. However, if they voluntarily remain, may they claim
uncontrolled[303] communication with their home State by
correspondence and couriers? When Mr. Washburne, the American
diplomatic envoy at Paris during the siege of that city in 1870 by the
Germans, claimed the right of sending a messenger with despatches
to London in a sealed bag through the German lines, Bismarck
declared that he was ready to allow foreign diplomatists in Paris to
send a courier to their home States once a week, but only under the
condition that their despatches were open and did not contain any
remarks concerning the war. Although the United States and other
Powers protested, Bismarck did not alter his decision. The whole
question must be treated as open.[304]
[303] The matter is discussed by Rolin-Jaequemyns in R.I. III. (1871), pp. 371-377.
[304] See above, vol. I. § 399, and Wharton, I. § 97.

Bombardment, how carried out.


§ 158. Regarding bombardment, article 26 of the Hague
Regulations enacts that the commander of the attacking forces shall
do all he can to notify his intention to resort to bombardment. But it
must be emphasised that a strict duty of notification for all cases of
bombardment is not thereby imposed, since it is only enacted that a
commander shall do all he can to send notification. He cannot do it
when the circumstances of the case prevent him, or when the
necessities of war demand an immediate bombardment. Be that as it
may, the purpose of notification is to enable private individuals
within the locality to be bombarded to seek shelter for their persons
and for their valuable personal property.
Article 27 of the Hague Regulations enacts the hitherto customary
rule that all necessary steps must be taken to spare as far as
possible all buildings devoted to religion, art, science, and charity;
further, historic monuments, hospitals, and all other places where
the sick and wounded are collected, provided these buildings,
places, and monuments are not used at the same time for military
purposes. To enable the attacking forces to spare these buildings
and places, the latter must be indicated by some particular signs,
which must be previously notified to the attacking forces and must
be visible from the far distance from which the besieging artillery
carries out the bombardment.[305]
[305] No siege takes place without the besieged accusing the besiegers of neglecting the
rule that buildings devoted to religion, art, charity, the tending of the sick, and the like,
must be spared during bombardments. The fact is that in case of a bombardment the
destruction of such buildings cannot always be avoided, although the artillery of the
besiegers do not intentionally aim at them. That the forces of civilised States
intentionally destroy such buildings, I cannot believe.
It must be specially observed that no legal duty exists for the
attacking forces to restrict bombardment to fortifications only. On
the contrary, destruction of private and public buildings through
bombardment has always been and is still considered lawful, as it is
one of the means to impress upon the authorities the advisability of
surrender. Some writers[306] assert either that bombardment of the
town, in contradistinction to the fortifications, is never lawful, or that
it is only lawful when bombardment of the fortifications has not
resulted in inducing surrender. But this opinion does not represent
the actual practice of belligerents, and the Hague Regulations do not
adopt it.
[306] See, for instance, Pillet, pp. 104-107; Bluntschli § 554A; Mérignhac, p. 180. Vattel
(III. § 169) does not deny the right to bombard the town, although he does not
recommend such bombardment.

X
ESPIONAGE AND TREASON

Vattel, III. §§ 179-182—Hall, § 188—Westlake, II. pp. 79 and 90—Lawrence, § 199—


Phillimore, III. § 96—Halleck, I. pp. 571-575, and in A.J. V.(1911), pp. 590-603—
Taylor, §§ 490 and 492—Wharton, III. § 347—Moore, VII. § 1132—Bluntschli, §§
563-564, 628-640—Heffter, § 125—Lueder in Holtzendorff, IV. pp. 461-467—
Ullmann, § 176—Bonfils, Nos. 1100-1104—Despagnet, Nos. 537-542—Pradier-
Fodéré, VI. Nos. 2762-2768—Rivier, II. pp. 282-284—Nys, III. pp. 256-263—Calvo,
IV. §§ 2111-2122—Fiore, III. Nos. 1341, 1374-1376, and Code, Nos. 1487-1490—
Martens, II. § 116—Longuet, §§ 63-75—Mérignhac, pp. 183-209—Pillet, pp. 97-
100—Zorn, pp. 174-195—Holland, War, Nos. 84-87—Bordwell, pp. 291-292—
Meurer, §§ 35-38—Spaight, pp. 202-215, 333-335—Ariga, §§ 98-100—Takahashi,
pp. 185-194—Friedemann, Die Lage der Kriegskundschafter und Spione (1892)—
Violle, L'espionage militaire en temps de guerre (1904)—Adler, Die Spionage (1906)
—Kriegsbrauch, pp. 30-31—Land Warfare, §§ 155-173—Bentwich in The Journal of
the Society of Comparative Legislation, New Series, X. (1909), pp. 243-299.

Twofold Character of Espionage and Treason.


§ 159. War cannot be waged without all kinds of information
about the forces and the intentions of the enemy and about the
character of the country within the zone of military operations. To
obtain the necessary information, it has always been considered
lawful, on the one hand, to employ spies, and, on the other, to make
use of the treason of enemy soldiers or private enemy subjects,
whether they were bribed[307] or offered the information voluntarily
and gratuitously. Article 24 of the Hague Regulations enacts the old
customary rule that the employment of methods necessary to obtain
information about the enemy and the country is considered
allowable. The fact, however, that these methods are lawful on the
part of the belligerent who employs them does not prevent the
punishment of such individuals as are engaged in procuring
information. Although a belligerent acts lawfully in employing spies
and traitors, the other belligerent, who punishes spies and traitors,
likewise acts lawfully. Indeed, espionage and treason bear a twofold
character. For persons committing acts of espionage or treason are—
as will be shown below in § 255—considered war criminals and may
be punished, but the employment of spies and traitors is considered
lawful on the part of the belligerents.
[307]Some writers maintain, however, that it is not lawful to bribe enemy soldiers into
espionage; see below, § 162.
Espionage in contradistinction to Scouting and Despatch-bearing.
§ 160. Espionage must not be confounded, firstly, with scouting,
or secondly, with despatch-bearing. According to article 29 of the
Hague Regulations, espionage is the act of a soldier or other
individual who clandestinely, or under false pretences, seeks to
obtain information concerning one belligerent in the zone of
belligerent operations with the intention of communicating it to the
other belligerent.[308] Therefore, soldiers not in disguise, who
penetrate into the zone of operations of the enemy, are not spies.
They are scouts who enjoy all privileges of the members of armed
forces, and they must, if captured, be treated as prisoners of war.
Likewise, soldiers or civilians charged with the delivery of despatches
for their own army or for that of the enemy and carrying out their
mission openly are not spies. And it matters not whether despatch-
bearers make use of balloons or of other means of communication.
Thus, a soldier or civilian trying to carry despatches from a force
besieged in a fortress to other forces of the same belligerent,
whether making use of a balloon or riding or walking at night, may
not be treated as a spy. On the other hand, spying can well be
carried out by despatch-bearers or by persons in a balloon, whether
they make use of the balloon of a despatch-bearer or rise in a
balloon for the special purpose of spying.[309] The mere fact that a
balloon is visible does not protect the persons using it from being
treated as spies; since spying can be carried out under false
pretences quite as well as clandestinely. But special care must be
taken really to prove the fact of espionage in such cases, for an
individual carrying despatches is prima facie not a spy and must not
be treated as a spy until proved to be such.
[308]Assisting or favouring espionage or knowingly concealing a spy are, according to a
customary rule of International Law, punishable as though they were themselves acts of
espionage; see Land Warfare, § 172.
[309] See below, § 356 (4), concerning wireless telegraphy.
A remarkable case of espionage is that of Major André,[310] which
occurred in 1780 during the American War of Independence. The
American General Arnold, who was commandant of West Point, on
the North River, intended to desert the Americans and join the
British forces. He opened negotiations with Sir Henry Clinton for the
purpose of surrendering West Point, and Major André was
commissioned by Sir Henry Clinton to make the final arrangements
with Arnold. On the night of September 21, Arnold and André met
outside the American and British lines, but André, after having
changed his uniform for plain clothes, undertook to pass the
American lines on his return, furnished with a passport under the
name of John Anderson by General Arnold. He was caught,
convicted as a spy, and hanged. As he was not seeking information,
[311]
and therefore was not a spy according to article 29 of the Hague
Regulations, a conviction for espionage would not, if such a case
occurred to-day, be justified. But it would be possible to convict for
war treason, for André was no doubt negotiating treason. Be that as
it may, George III. considered André a martyr, and honoured his
memory by granting a pension to his mother and a baronetcy to his
brother.[312]
[310] See Halleck in A.J. V. (1911), p. 594.
[311] Halleck, loc. cit., p. 598, asserts the contrary.
[312] See Phillimore, III. § 106; Halleck, I. p. 575; Rivier, II. p. 284.

Punishment of Espionage.
§ 161. The usual punishment for spying is hanging or shooting,
but less severe punishments are, of course, admissible and
sometimes inflicted. However this may be, according to article 30 of
the Hague Regulations a spy may not be punished without a trial
before a court-martial. And according to article 31 of the Hague
Regulations a spy who is not captured in the act but rejoins the
army to which he belongs, and is subsequently captured by the
enemy, may not be punished for his previous espionage and must be
treated as a prisoner of war. But it must be specially observed that
article 31 concerns only such spies as belong to the armed forces of
the enemy; civilians who act as spies and are captured later may be
punished. Be that as it may, no regard is paid to the status, rank,
position, or motive of a spy. He may be a soldier or a civilian, an
officer or a private. He may be following instructions of superiors or
acting on his own initiative from patriotic motives. A case of
espionage, remarkable on account of the position of the spy, is that
of the American Captain Nathan Hale, which occurred in 1776. After
the American forces had withdrawn from Long Island, Captain Hale
recrossed under disguise and obtained valuable information about
the English forces that had occupied the island. But he was caught
before he could rejoin his army, and he was executed as a spy.[313]
[313]The case of Major Jakoga and Captain Oki, which, though reported as a case of
espionage, is really a case of treason, will be discussed below in § 255.

Treason.
§ 162. Treason can be committed by a soldier or an ordinary
subject of a belligerent, but it can also be committed by an
inhabitant of an occupied enemy territory or even by the subject of a
neutral State temporarily staying there, and it can take place after
an arrangement with the favoured belligerent or without such an
arrangement. In any case a belligerent making use of treason acts
lawfully, although the Hague Regulations do not mention the matter
at all. But many acts of different sorts can be treasonable; the
possible cases of treason and the punishment of treason will be
discussed below in § 255.
Although it is generally recognised that a belligerent acts lawfully
who makes use of the offer of a traitor, the question is
controversial[314] whether a belligerent acts lawfully who bribes a
commander of an enemy fortress into surrender, incites enemy
soldiers to desertion, bribes enemy officers for the purpose of
getting important information, incites enemy subjects to rise against
the legitimate Government, and the like. If the rules of the Law of
Nations are formulated, not from doctrines of book-writers, but from
what is done by the belligerents in practice,[315] it must be asserted
that such acts, detestable and immoral as they are, are not
considered illegal according to the Law of Nations.
[314] See Vattel, III. § 180; Heffter, § 125; Taylor, § 490; Martens, II. § 110 (8); Longuet,
§ 52; Mérignhac, p. 188, and others. See also below, § 164.
[315] See Land Warfare, § 158.

XI
RUSES

Grotius, III. c. 1, §§ 6-18—Bynkershoek, Quaest. jur. publ. I. c. 1—Vattel, III. §§


177-178—Hall, § 187—Lawrence, § 207—Westlake, II. p. 73—Phillimore, III. § 94
—Halleck, I. pp. 566-571—Taylor, § 488—Moore, VII. § 1115—Bluntschli, §§ 565-
566—Heffter, § 125—Lueder in Holtzendorff, IV. pp. 457-461—Ullmann, § 176—
Bonfils, Nos. 1073-1075—Despagnet, Nos. 526-527—Pradier-Fodéré, VI. Nos.
2759-2761—Rivier, II. p. 261—Nys, III. pp. 252-255—Calvo, IV. §§ 2106-2110—
Fiore, III. Nos. 1334-1339—Longuet, §§ 53-56—Mérignhac, pp. 165-168—Pillet,
pp. 93-97—Kriegsbrauch, pp. 23-24—Holland, War, Nos. 78-79—Bordwell, pp. 283-
286—Meurer, II pp. 151-152—Spaight, pp. 152-156—Land Warfare, §§ 139-154—
Brocher in R.I. V. (1873), pp. 325-329.

Character of Ruses of War.


§ 163. Ruses of war or stratagems are deceit employed during
military operations for the purpose of misleading the enemy. Such
deceit is of great importance in war, and, just as belligerents are
allowed to employ all methods of obtaining information, so they are,
on the other hand, and article 24 of the Hague Regulations confirms
this, allowed to employ all sorts of ruses for the purpose of deceiving
the enemy. Very important objects can be attained through ruses of
war, as, for instance, the surrender of a force or of a fortress, the
evacuation of territory held by the enemy, the withdrawal from a
siege, the abandonment of an intended attack, and the like. But
ruses of war are also employed, and are very often the decisive
factor, during battles.
Different kinds of Stratagems.
§ 164. Of ruses there are so many kinds that it is impossible to
enumerate[316] and classify them. But in order to illustrate acts
carried out as ruses some instances may be given. It is hardly
necessary to mention the laying of ambushes and traps, the masking
of military operations such as marches or the erection of batteries
and the like, the feigning of attacks or flights or withdrawals, the
carrying out of a surprise, and other stratagems employed every day
in war. But it is important to know that, when useful, feigned signals
and bugle-calls may be ordered, the watchword of the enemy may
be used, deceitful intelligence may be disseminated,[317] the signals
and the bugle-calls of the enemy may be mimicked[318] to mislead his
forces. And even such detestable acts[319] as bribery of enemy
commanders and officials in high position, and secret seduction of
enemy soldiers to desertion, and of enemy subjects to insurrection,
are frequently committed, although many writers protest. As regards
the use of the national flag, the military ensigns, and the uniforms of
the enemy, theory and practice are unanimous in rejecting it during
actual attack and defence, since the principle is considered inviolable
that during actual fighting belligerent forces ought to be certain who
is friend and who is foe. But many[320] publicists maintain that until
the actual fighting begins belligerent forces may by way of
stratagem make use of the national flag, military ensigns, and
uniforms of the enemy. Article 23 (f) of the Hague Regulations does
not prohibit any and every use of these symbols, but only their
improper use, thus leaving the question open,[321] what uses are
proper and what are not. Those who have hitherto taught the
admissibility of the use of these symbols outside actual fighting can
correctly maintain that the quoted article 23 (f) does not prohibit it.
[322]

[316] See Land Warfare, § 144, where a great number of legitimate ruses are
enumerated.
[317] See the examples quoted by Pradier-Fodéré, VI. No. 2761.
[318] See Pradier-Fodéré, VI. No. 2760.
[319] The point has been discussed above in § 162.
[320] See, for instance, Hall, § 187; Bluntschli, § 565; Taylor, § 488; Calvo, IV. No. 2106;
Pillet, p. 95; Longuet, § 54. But, on the other hand, the number of publicists who
consider it illegal to make use of the enemy flag, ensigns, and uniforms, even before an
actual attack, is daily becoming larger; see, for instance, Lueder in Holtzendorff, IV. p.
458; Mérignhac, p. 166; Pradier-Fodéré, VI. No. 2760; Bonfils, No. 1074; Kriegsbrauch,
p. 24. As regards the use of the enemy flag on the part of men-of-war, see below, in §
211.
[321] Some writers maintain that article 23 (f) of the Hague Regulations has settled the
controversy, but they forget that this article speaks only of the improper use of the
enemy ensigns and uniform. See Land Warfare, § 152.
[322] The use of the enemy uniform for the purpose of deceit is different from the case
when members of armed forces who are deficient in clothes wear the uniforms of
prisoners or of the enemy dead. If this is done—and it always will be done if necessary—
such distinct alterations in the uniform ought to be made as will make it apparent to
which side the soldiers concerned belong (see Land Warfare, § 154). Different again is
the case where soldiers are, through lack of clothing, obliged to wear the apparel of
civilians, such as greatcoats, hats, and the like. Care must then be taken that the soldiers
concerned do nevertheless wear a fixed distinctive emblem which marks them as
soldiers, since otherwise they lose the privileges of members of the armed forces of the
belligerents (see article 1, No. 2, of the Hague Regulations). During the Russo-Japanese
War both belligerents repeatedly accused each other of using Chinese clothing for
members of their armed forces; the soldiers concerned apparently were obliged through
lack of proper clothing temporarily to make use of Chinese garments. See, however,
Takahashi, pp. 174-178.

Stratagems in contradistinction to Perfidy.


§ 165. Stratagems must be carefully distinguished from perfidy,
since the former are allowed, whereas the latter is prohibited.
Halleck (I. p. 566) correctly formulates the distinction by laying
down the principle that, whenever a belligerent has expressly or
tacitly engaged and is therefore bound by a moral obligation to
speak the truth to an enemy, it is perfidy to betray the latter's
confidence, because it contains a breach of good faith.[323] Thus a
flag of truce or the cross of the Geneva Convention must never be
made use of for a stratagem, capitulations must be carried out to
the letter, the feigning of surrender for the purpose of luring the
enemy into a trap is a treacherous act, as is the assassination of
enemy commanders or soldiers or heads of States. On the other
hand, stratagem may be met by stratagem, and a belligerent cannot
complain of the enemy who so deceives him. If, for instance, a spy
of the enemy is bribed to give deceitful intelligence to his employer,
or if an officer, who is approached by the enemy and offered a bribe,
accepts it feigningly but deceives the briber and leads him to
disaster, no perfidy is committed.
[323] See Land Warfare, §§ 139-142, 146-150.

XII
OCCUPATION OF ENEMY TERRITORY

Grotius, III. c. 6, § 4—Vattel, III. §§ 197-200—Hall, §§ 153-161—Westlake, II. pp.


83-106—Lawrence, §§ 176-179—Maine, pp. 176-183—Halleck, II. pp. 432-466—
Taylor, §§ 568-579—Wharton, III. §§ 354-355—Moore, VII. §§ 1143-1155—
Bluntschli, §§ 539-551—Heffter, §§ 131-132—Lueder in Holtzendorff, IV. pp. 510-
524—Klüber, §§ 255-256—G. F. Martens, II. § 280—Ullmann, § 183—Bonfils, Nos.
1156-1175—Despagnet, Nos. 567-578—Pradier-Fodéré, VII. Nos. 2939-2988,
3019-3028—Nys, III. pp. 309-351—Rivier, II. pp. 299-306—Calvo, IV. §§ 2166-
2198—Fiore, III. Nos. 1454-1481, and Code, Nos. 1535-1563—Martens, II. §§ 117-
119—Longuet, §§ 115-133—Mérignhac, pp. 241-262—Pillet, pp. 237-259—Zorn,
pp. 213-243—Kriegsbrauch, pp. 45-50—Holland, War, Nos. 102-106—Bordwell, pp.
312-330—Meurer, II. §§ 45-55—Spaight, pp. 320-380—Land Warfare, §§ 340-405
—Waxel, L'armée d'invasion el la population (1874)—Litta, L'occupazione militare
(1874)—Löning, Die Verwaltung des General-Gouvernements im Elsass (1874), and
in R.I. IV. (1872), p. 622, V. (1873), p. 69—Bernier, De l'occupation militaire en
temps de guerre (1884)—Corsi, L'occupazione militare in tempo di guerra e le
relazione internazionale che ne derivano (2nd edit. 1886)—Bray, De l'occupation
militaire en temps de guerre, etc. (1891)—Magoon, Law of Civil Government under
Military Occupation (2nd edit. 1900)—Lorriot, De la nature de l'occupation de
guerre (1903)—Deherpe, Essai sur le developpement de l'occupation en droit
international (1903)—Sichel, Die kriegerische Besetzung feindlichen Staatsgebietes
(1905)—Nowacki, Die Eisenbahnen im Kriege (1906), pp. 78-90—Rolin-
Jaequemyns in R.I. II. (1870), p. 666, and III. (1871), p. 311.

Occupation as an Aim of Warfare.


§ 166. If a belligerent succeeds in occupying a part or even the
whole of the enemy territory, he has realised a very important aim of
warfare. He can now not only make use of the resources of the
enemy country for military purposes, but can also keep it for the
time being as a pledge of his military success, and thereby impress
upon the enemy the necessity of submitting to terms of peace. And
in regard to occupation, International Law respecting warfare has
progressed more than in any other department. In former times
enemy territory that was occupied by a belligerent was in every
point considered his State property, with which and with the
inhabitants therein he could do what he liked. He could devastate
the country with fire and sword, appropriate all public and private
property therein, kill the inhabitants, or take them away into
captivity, or make them take an oath of allegiance. He could, even
before the war was decided and his occupation was definitive,
dispose of the territory by ceding it to a third State, and an instance
of this happened during the Northern War (1700-1718), when in
1715 Denmark sold the occupied Swedish territories of Bremen and
Verden to Hanover. That an occupant could force the inhabitants of
the occupied territory to serve in his own army and to fight against
their legitimate sovereign, was indubitable. Thus, during the Seven
Years' War, Frederick II. of Prussia repeatedly made forcible levies of
thousands of recruits in Saxony, which he had occupied. But during
the second half of the eighteenth century things gradually began to
undergo a change. That the distinction between mere temporary
military occupation of territory, on the one hand, and, on the other,
real acquisition of territory through conquest and subjugation,
became more and more apparent, is shown by the fact that Vattel
(III. § 197) drew attention to it. However, it was not till long after
the Napoleonic wars in the nineteenth century that the
consequences of this distinction were carried to their full extent by
the theory and practice of International Law. So late as 1808, after
the Russian troops had militarily occupied Finland, which was at that
time a part of Sweden, Alexander I. of Russia made the inhabitants
take an oath of allegiance,[324] although it was only by article 4 of the
Peace Treaty of Frederikshamm[325] of September 17, 1809, that
Sweden ceded Finland to Russia. The first writer who drew all the
consequences of the distinction between mere military occupation
and real acquisition of territory was Heffter in his treatise Das
Europaeische Völkerrecht der Gegenwart (§ 131), which made its
appearance in 1844. And it is certain that it took the whole of the
nineteenth century to develop such rules regarding occupation as
are now universally recognised and in many respects enacted by
articles 42-56 of the Hague Regulations.
[324] See Martens, N.R. I. p. 9.
[325] See Martens, N.R. I. p. 19.
In so far as these rules touch upon the special treatment of
persons and property of the inhabitants of, and public property
situated within, occupied territory, they have already been taken into
consideration above in §§ 107-154. What concerns us here are the
rights and duties of the occupying belligerent in relation to his
political administration of the territory and to his political authority
over its inhabitants.[326] The principle underlying these modern rules
is that, although the occupant does in no wise acquire sovereignty
over such territory through the mere fact of having occupied it, he
actually exercises for the time being a military authority over it. As
he thereby prevents the legitimate Sovereign from exercising his
authority and claims obedience for himself from the inhabitants, he
has to administer the country not only in the interest of his own
military advantage, but also, so far as possible at any rate, for the
public benefit of the inhabitants. Thus the present International Law
not only gives certain rights to an occupant, but also imposes certain
duties upon him.
[326]The Hague Regulations (Section III. articles 42-56), and all the French writers, but
also many others, treat under the heading "occupation" not only of the rights and duties
of an occupant concerning the political administration of the country and the political
authority over the inhabitants, but also of other matters, such as appropriation of public
and private property, requisitions and contributions, and destruction of public and private
property, violence against private enemy subjects and enemy officials. These matters
have, however, nothing to do with occupation, but are better discussed in connection
with the means of land warfare; see above, §§ 107-154.

Occupation, when effected.


§ 167. Since an occupant, although his power is merely military,
has certain rights and duties, the first question to deal with is, when
and under what circumstances a territory must be considered
occupied.
Now it is certain that mere invasion is not occupation. Invasion is
the marching or riding of troops—or the flying of a military air vessel
—into enemy country. Occupation is invasion plus taking possession
of enemy country for the purpose of holding it, at any rate
temporarily. The difference between mere invasion and occupation
becomes apparent by the fact that an occupant sets up some kind of
administration, whereas the mere invader does not. A small
belligerent force can raid enemy territory without establishing any
administration, but quickly rush on to some place in the interior for
the purpose of reconnoitring, of destroying a bridge or depôt of
munitions and provisions, and the like, and quickly withdraw after
having realised its purpose.[327] Although it may correctly be asserted
that, so long and in so far as such raiding force is in possession of a
locality and sets up a temporary administration therein, it occupies
this locality, yet it certainly does not occupy the whole territory, and
even the occupation of such locality ceases the moment the force
withdraws.
[327] See Land Warfare, § 343.
However this may be, as a rule occupation will be coincident with
invasion. The troops march into a district, and the moment they get
into a village or town—unless they are actually fighting their way—
they take possession of the Municipal Offices, the Post Office, the
Police Stations, and the like, and assert their authority there. From
the military point of view such villages and towns are now
"occupied." Article 42 of the Hague Regulations enacts that territory
is considered occupied when it is actually placed under the authority
of the hostile army, and that such occupation applies only to the
territory where that authority is established and in a position to
assert itself. This definition of occupation is not at all precise, but it
is as precise as a legal definition of such kind of fact as occupation
can be. If, as some publicists[328] maintain, only such territory were
actually occupied, in which every part is held by a sufficient number
of soldiers to enforce immediately and on the very spot the authority
of an occupant, an effective occupation of a large territory would be
impossible, since then not only in every town, village, and railway
station, but also in every isolated habitation and hut the presence of
a sufficient number of soldiers would be necessary. Reasonably no
other conditions ought to be laid down as necessary to constitute
effective occupation in war than those under which in time of peace
a Sovereign is able to assert his authority over a territory. What
these conditions are is a question of fact which is to be answered
according to the merits of the special case. When the legitimate
Sovereign is prevented from exercising his powers and the occupant,
being able to assert his authority, actually establishes an
administration over a territory, it matters not with what means and
in what ways his authority is exercised. For instance, when in the
centre of a territory a large force is established from which flying
columns are constantly sent round the territory, such territory is
indeed effectively occupied, provided there are no enemy forces
present, and, further, provided these columns can really keep the
territory concerned under control.[329] Again, when an army is
marching on through enemy territory, taking possession of the lines
of communication and the open towns, surrounding the fortresses
with besieging forces, and disarming the inhabitants in open places
of habitation, the whole territory left behind the army is effectively
occupied, provided some kind of administration is established, and
further provided that, as soon as it becomes necessary to assert the
authority of the occupant, a sufficient force can within reasonable
time be sent to the locality affected. The conditions vary with those
of the country concerned. When a vast country is thinly populated, a
smaller force is necessary to occupy it, and a smaller number of
centres need be garrisoned than in the case of a thickly populated
country. Thus, the occupation of the former Orange Free State and
the former South African Republic became effective in 1901 some
time after their annexation by Great Britain and the degeneration of
ordinary war into guerilla war, although only about 250,000 British
soldiers had to keep up the occupation of a territory of about
500,000 square miles. The fact that all the towns and all the lines of
communication were in the hands and under the administration of
the British army, that the inhabitants of smaller places were taken
away into concentration camps, that the enemy forces were either in
captivity or dispersed into comparatively small guerilla bands, and
finally, that wherever such bands tried to make an attack, a
sufficient British force could within reasonable time make its
appearance, was quite sufficient to assert British authority[330] over
that vast territory, although it was more than a year before peace
was finally established.
[328] See, for instance, Hall, § 161. This was also the standpoint of the delegates of the
smaller States at the Brussels Conference of 1874 when the Declaration of Brussels was
drafted.
[329] This is not identical with so-called constructive occupation, but is really effective
occupation. An occupation is constructive only if an invader declares districts as occupied
over which he actually does not exercise control—for instance, when he actually occupies
only the capital of a large province, and proclaims that he has thereby occupied the
whole of the province, although he does not take any steps to exercise control over it.
[330] The annexation of the Orange Free State dates from May 24, 1900, and that of the
South African Republic from September 1, 1900. It may well be doubted whether at
these dates the occupation of the territories concerned was already so complete as to be
called effective. The British Government ought not, therefore, to have proclaimed the
annexation at such early dates. But there ought to be no doubt that the occupation
became effective some time afterwards, in 1901. See, however, Sir Thomas Barclay in
The Law Quarterly Review, XXI. (1905), p. 307, who asserts the contrary; see also,
below, § 264, p. 326, note 2, and § 265, p. 327, note 1. The Times' History of the War in
South Africa (vol. V. p. 251) estimates the number of Boer fighters in May 1901 to be
about 13,000. These armed men were dispersed into a very large number of guerilla
bands, and they were in a great many cases men who seemingly had submitted to the
British authorities, but afterwards had taken up arms.
It must be emphasised that the rules regarding effective
occupation must be formulated on the basis of actual practice quite
as much as rules regarding other matters of International Law.
Those rules are not authoritative which are laid down by theorists,
but only those which are abstracted from the actual practice of
warfare and are unopposed by the Powers.[331]
[331] The question is so much controverted that it is impossible to enumerate the
different opinions. Readers who want to study the question must be referred to the
literature quoted above at the commencement of § 166.

Occupation, when ended.


§ 168. Occupation comes to an end when an occupant withdraws
from a territory or is driven out of it. Thus, occupation remains only
over a limited area of a territory if the forces in occupation are
drawn into a fortress on that territory and are there besieged by the
re-advancing enemy, or if the occupant concentrates his forces in a
certain place of the territory, withdrawing before the re-advancing
enemy. But occupation does not cease because the occupant, after
having disarmed the inhabitants and having made arrangements for
the administration of the country, is marching on to overtake the
retreating enemy, leaving only comparatively few soldiers behind.
Rights and Duties in General of the Occupant.
§ 169. As the occupant actually exercises authority, and as the
legitimate Government is prevented from exercising its authority, the
occupant acquires a temporary right of administration over the
respective territory and its inhabitants. And all steps he takes in the
exercise of this right must be recognised by the legitimate
Government after occupation has ceased. This administration is in no
wise to be compared with ordinary administration, for it is distinctly
and precisely military administration. In carrying it out the occupant
is, on the one hand, totally independent of the Constitution and the
laws of the respective territory, since occupation is an aim of
warfare, and since the maintenance and safety of his forces and the
purpose of war stand in the foreground of his interest and must be
promoted under all circumstances and conditions. But, although as
regards the safety of his army and the purpose of war the occupant
is vested with an almost absolute power, he is not the Sovereign of
the territory, and therefore has no right to make changes in the laws
or in the administration except those which are temporarily
necessitated by his interest in the maintenance and safety of his
army and the realisation of the purpose of war. On the contrary, he
has the duty of administrating the country according to the existing
laws and the existing rules of administration; he must insure public
order and safety, must respect family honour and rights, individual
lives, private property, religious convictions and liberty. Article 43 of
the Hague Regulations enacts the following rule which is of
fundamental importance: "The authority of the legitimate Power
having actually passed into the hands of the occupant, the latter
shall take all steps in his power to re-establish and insure, as far as
possible, public order and safety, while respecting, unless absolutely
prevented, the laws in force in the country."

Rights of the Occupant regarding the Inhabitants.


§ 170. An occupant having authority over the territory, the
inhabitants are under his sway and have to render obedience to his
commands. However, the power of the occupant over the inhabitants
is not unrestricted, for articles 23, 44, and 45 of the Hague
Regulations expressly enact, that he is prohibited from compelling
the inhabitants to take part in military operations against the
legitimate Government, to give information concerning the army of
the other belligerent or concerning the latter's means of defence, or
to take an oath of allegiance. On the other hand, he may compel
them to take an oath—sometimes called an "oath of neutrality"—to
abstain from taking up a hostile attitude against the occupant and
willingly to submit to his legitimate commands; and he may punish
them severely for breaking this oath. He may make requisitions and
demand contributions[332] from them, may compel them to render
services as drivers, farriers, and the like.[333] He may compel them to
render services for the repair or the erection of such roads,
buildings, or other works as are necessary for military operations.[334]
He may also collect the ordinary taxes, dues, and tolls imposed for
the benefit of the State by the legitimate Government. But in such
case he is, according to article 48 of the Hague Regulations, obliged
to make the collection, as far as possible, in accordance with the
rules in existence and the assessment in force, and he is, on the
other hand, bound to defray the expenses of the administration of
the occupied territory on the same scale as that by which the
legitimate Government was bound.
[332] See above, §§ 147 and 148.
[333] Formerly he could likewise compel them to render services as guides, but this is
now prohibited by the wording which article 44 received from the Second Peace
Conference. It should, however, be mentioned that Germany, Austria-Hungary, Japan,
Montenegro, and Russia have signed Convention IV. with a reservation against article 44,
and that in a war with these Powers the old rule is valid that inhabitants may be
compelled to serve as guides.
[334] See article 52 of the Hague regulations, and Land Warfare, §§ 388-392.

Whoever does not comply with his commands, or commits a


prohibited act, may be punished by him; but article 50 of the Hague
Regulations expressly enacts the rule that no general penalty,
pecuniary or otherwise, may be inflicted on the population on
account of the acts of individuals for which it cannot be regarded as
collectively responsible. It must, however, be specially observed that
this rule does not at all prevent[335] reprisals on the part of
belligerents occupying enemy territory. In case acts of illegitimate
warfare are committed by enemy individuals not belonging to the
armed forces, reprisals may be resorted to, although practically
innocent individuals are thereby punished for illegal acts for which
they are neither legally nor morally responsible—for instance, when
a village is burned by way of reprisal for a treacherous attack
committed there on enemy soldiers by some unknown individuals.
[336]
Nor does this new rule prevent an occupant from taking
hostages[337] in the interest of the safety of the line of
communication threatened by guerillas not belonging to the armed
forces, or for other purposes,[338] although the hostage must suffer
for acts or omissions of others for which he is neither legally nor
morally responsible.
[335] See Holland, War, No. 110, and Land Warfare, §§ 385-386. See also Zorn, pp. 239-
243, where an important interpretation of article 50 is discussed.
[336] See below, § 248.
[337] But this is a moot point; see below, § 259.
[338]Belligerents sometimes take hostages for the purpose of securing compliance with
demands for contributions, requisitions, and the like. As long as such hostages obtain the
same treatment as prisoners of war, the practice does not seem to be illegal, although
the Hague Regulations do not mention and many publicists condemn it; see above, §
116, p. 153, note 1, and below, § 259, p. 319, note 2.
It must be particularly noted that in the treatment of the
inhabitants of enemy territory the occupant need not make any
difference between such as are subjects of the enemy and such as
are subjects of neutral States.[339]
[339]See above,§ 88, and Frankenbach, Die Rechtsstellung von neutralen
Staatsangehörigen in kriegführenden Staaten (1910), pp. 46-50.
And it must be further observed that, according to British and
American views—see above, § 100a—article 23 (h) of the Hague
Regulations prohibits an occupant of enemy territory from declaring
extinguished, suspended, or unenforceable in a Court of Law the
rights and the rights of action of the inhabitants.

Position of Government Officials and Municipal Functionaries during Occupation.


§ 171. As through occupation authority over the territory actually
passes into the hands of the occupant, he may for the time of his
occupation depose all Government officials and municipal
functionaries that have not withdrawn with the retreating enemy. On
the other hand, he must not compel them by force to carry on their
functions during occupation, if they refuse to do so, except where a
military necessity for the carrying on of a certain function arises. If
they are willing to serve under him, he may make them take an oath
of obedience, but not of allegiance, and he may not compel them to
carry on their functions in his name, but he may prevent them from
doing so in the name of the legitimate Government.[340] Since,
according to article 43 of the Hague Regulations, he has to secure
public order and safety, he must temporarily appoint other
functionaries in case those of the legitimate Government refuse to
serve under him, or in case he deposes them for the time of the
occupation.
[340]Many publicists assert that in case an occupant leaves officials of the legitimate
Government in office, he "must" pay them their ordinary salaries. But I cannot see that
there is a customary or conventional rule in existence concerning this point. But it is in
an occupant's own interest to pay such salaries. and he will as a rule do this. Only in the
case of article 48 of the Hague Regulations is he compelled to do it.

Position of Courts of Justice during Occupation.


§ 172. The particular position which Courts of Justice have
nowadays in civilised countries, makes it necessary to discuss their
position during occupation.[341] There is no doubt that an occupant
may suspend the judges as well as other officials. However, if he
does suspend them, he must temporarily appoint others in their
place. If they are willing to serve under him, he must respect their
independence according to the laws of the country. Where it is
necessary, he may set up military Courts instead of the ordinary
Courts. In case and in so far as he admits the administration of
justice by the ordinary Courts, he may nevertheless, so far as it is
necessary for military purposes or for the maintenance of public
order and safety, temporarily alter the laws, especially the Criminal
Law, on the basis of which justice is administered, as well as the
laws regarding procedure. He has, however, no right to constrain the
Courts to pronounce their verdicts in his name, although he need not
allow them to pronounce verdicts in the name of the legitimate
Government. A case that happened during the Franco-German War
may serve as an illustration. In September 1870, after the fall of the
Emperor Napoleon and the proclamation of the French Republic, the
Court of Appeal at Nancy pronounced its verdicts under the formula
"In the name of the French Government and People." Since Germany
had not yet recognised the French Republic, the Germans ordered
the Court to use the formula "In the name of the High German
Powers occupying Alsace and Lorraine," but gave the Court to
understand that, if the Court objected to this formula, they were
disposed to admit another, and were even ready to admit the
formula "In the name of the Emperor of the French," as the Emperor
had not abdicated. The Court, however, refused to pronounce its
verdict otherwise than "In the name of the French Government and
People," and, consequently, suspended its sittings. There can be no
doubt that the Germans had no right to order the formula, "In the
name of the High German Powers, &c.," to be used, but they were
certainly not obliged to admit the formula preferred by the Court;
and the fact that they were disposed to admit another formula than
that at first ordered ought to have made the Court accept a
compromise. Bluntschli (§ 547) correctly maintains that the most
natural solution of the difficulty would have been to use the neutral
formula "In the name of the Law."
[341] See Petit, L'Administration de la justice en territoire occupé (1900).

CHAPTER IV
WARFARE ON SEA

I
ON SEA WARFARE IN GENERAL

Hall, § 147—Lawrence, §§ 193-194—Westlake, II. pp. 120-132—Maine, pp. 117-122


—Manning, pp. 183-184—Phillimore, III. § 347—Twiss, II. § 73—Halleck, II. pp.
80-82—Taylor, § 547—Wharton, III. §§ 342-345—Wheaton, § 355—Bluntschli, §§
665-667—Heffter, § 139—Geffcken in Holtzendorff, IV. pp. 547-548, 571-581—
Ullmann, §§ 187-188—Bonfils, Nos. 1268, 1294-1338—Despagnet, Nos. 647-649—
Pradier-Fodéré, VIII. Nos. 3066-3090, 3107-3108—Nys, III. pp. 433-466—Rivier, II.
pp. 329-335—Calvo, IV. §§ 2123, 2379-2410—Fiore, III. Nos. 1399-1413—Pillet,
pp. 118-120—Perels, § 36—Testa, pp. 147-157—Boeck, Nos. 3-153—Lawrence,
Essays, pp. 278-306—Westlake, Chapters, pp. 245-253—Ortolan, I. pp. 35-50—
Hautefeuille, I. pp. 161-167—Gessner, Westlake, Lorimer, Rolin-Jaequemyns,
Laveleye, Albéric Rolin, and Pierantoni in R.I. VII. (1875), pp. 256-272 and 558-
656—Twiss, in R.I. XVI. (1884), pp. 113-137—See also the authors quoted below,
§ 178, p. 223, note 1.

Aims and Means of Sea Warfare.


§ 173. The purpose of war is the same in the case of warfare on
land or on sea—namely, the overpowering of the enemy. But sea
warfare serves this purpose by attempting the accomplishment of
aims different from those of land warfare. Whereas the aims of land
warfare are defeat of the enemy army and occupation of the enemy
territory, the aims[342] of sea warfare are: defeat of the enemy navy;
annihilation of the enemy merchant fleet; destruction of enemy
coast fortifications, and of maritime as well as military
establishments on the enemy coast; cutting off intercourse with the
enemy coast; prevention of carriage of contraband and of rendering
unneutral service to the enemy; all kinds of support to military
operations on land, such as protection of a landing of troops on the
enemy coast; and lastly, defence of the home coast and protection
to the home merchant fleet.[343] The means by which belligerents in
sea warfare endeavour to realise these aims are: attack on and
seizure of enemy vessels, violence against enemy individuals,
appropriation and destruction of enemy vessels and goods carried by
them, requisitions and contributions, bombardment of the enemy
coast, cutting of submarine cables, blockade, espionage, treason,
ruses, capture of neutral vessels carrying contraband or rendering
unneutral service.
[342] Aims of sea warfare must not be confounded with ends of war; see above, § 66.
[343] Article 1 of the U.S. Naval War Code enumerates the following as aims of sea
warfare:—The capture or destruction of the military and naval forces of the enemy, of his
fortifications, arsenals, dry docks, and dockyards, of his various military and naval
establishments, and of his maritime commerce; to prevent his procuring war material
from neutral sources; to aid and assist military operations on land; to protect and defend
the national territory, property, and sea-borne commerce.

Lawful and Unlawful Practices of Sea Warfare.


§ 174. As regards means of sea warfare, just as regards means of
land warfare, it must be emphasised that not every practice capable
of injuring the enemy in offence and defence is lawful. Although no
regulations regarding the laws of war on sea have as yet been
enacted by a general law-making treaty as a pendant to the Hague
Regulations, there are treaties concerning special points—such as
submarine mines, bombardment by naval forces, and others—and
customary rules of International Law in existence which regulate the
matter. Be that as it may, the rules concerning sea warfare are in
many points identical with, but in many respects differ from, the
rules in force regarding warfare on land. Therefore, the means of
sea warfare must be discussed separately in the following sections.
But blockade and capture of vessels carrying contraband and
rendering unneutral service to the enemy, although they are means
of warfare against an enemy, are of such importance as regards
neutral trade that they will be discussed below in Part III. §§ 368-
413.

Objects of the Means of Sea Warfare.


§ 175. Whereas the objects against which means of land warfare
may be directed are innumerable, the number of the objects against
which means of sea warfare are directed is very limited, comprising
six objects only. The chief object is enemy vessels, whether public or
private; the next, enemy individuals, with distinction between those
taking part in fighting and others; the third, enemy goods on enemy
vessels; the fourth, the enemy coast; the fifth and sixth, neutral
vessels attempting to break blockade, carrying contraband, or
rendering unneutral service to the enemy.
Development of International Law regarding Private Property on Sea.
§ 176. It is evident that in times when a belligerent could destroy
all public and private enemy property he was able to seize, no
special rule existed regarding private enemy ships and private enemy
property carried by them on the sea. But the practice of sea warfare
frequently went beyond the limits of even so wide a right, treating
neutral goods on enemy ships as enemy goods, and treating neutral
ships carrying enemy goods as enemy ships. It was not until the
time of the Consolato del Mare in the fourteenth century that a set
of clear and definite rules with regard to private enemy vessels and
private enemy property on sea in contradistinction to neutral ships
and neutral goods was adopted. According to this famous collection
of maritime usages observed by the communities of the
Mediterranean, there is no doubt that a belligerent may seize and
appropriate all private enemy ships and goods. But a distinction is
made in case of either ship or goods being neutral. Although an
enemy ship may always be appropriated, neutral goods thereon
have to be restored to the neutral owners. On the other hand,
enemy goods on neutral ships may be appropriated, but the neutral
ships carrying such goods must be restored to their owners.
However, these rules of the Consolato del Mare were not at all
generally recognised, although they were adopted by several treaties
between single States during the fourteenth and fifteenth centuries.
Neither the communities belonging to the Hanseatic League, nor the
Netherlands and Spain during the War of Independence, nor
England and Spain during their wars in the sixteenth century,
adopted these rules. And France expressly enacted by Ordinances of
1543 (article 42) and 1583 (article 69) that neutral goods on enemy
ships as well as neutral ships carrying enemy goods should be
appropriated.[344] Although France adopted in 1650 the rules of the
Consolato del Mare, Louis XIV. dropped them again by the Ordinance
of 1681 and re-enacted that neutral goods on enemy ships and
neutral ships carrying enemy goods should be appropriated. Spain
enacted the same rules in 1718. The Netherlands, in
contradistinction to the Consolato del Mare, endeavoured by a
number of treaties to foster the principle that the flag covers the
goods, so that enemy goods on neutral vessels were exempt from,
whereas neutral goods on enemy vessels were subject to,
appropriation. On the other hand, throughout the eighteenth and
during the nineteenth century down to the beginning of the Crimean
War in 1854, England adhered to the rules of the Consolato del
Mare. Thus, no generally accepted rules of International Law
regarding private property on sea were in existence.[345] Matters
were made worse by privateering, which was generally recognised
as lawful, and by the fact that belligerents frequently declared a
coast blockaded without having a sufficient number of men-of-war
on the spot to make the blockade effective. It was not until the
Declaration of Paris in 1856 that general rules of International Law
regarding private property on sea came into existence.
[344] Robe d'ennemy confisque celle d'amy. Confiscantur ex navibus res, ex rebus naves.
[345] Boeck, Nos. 3-103, and Geffcken in Holtzendorff, IV. pp. 572-578, give excellent
summaries of the facts.

Declaration of Paris.
§ 177. Things began to undergo a change with the outbreak of the
Crimean War in 1854, when all the belligerents proclaimed that they
would not issue Letters of Marque, and when, further, Great Britain
declared that she would not seize enemy goods on neutral vessels,
and when, thirdly, France declared that she would not appropriate
neutral goods on enemy vessels. Although this alteration of attitude
on the part of the belligerents was originally intended for the
Crimean War only and exceptionally, it led after the conclusion of
peace in 1856 to the famous and epoch-making Declaration of Paris,
[346]
which enacted the four rules—(1) that privateering is abolished,
(2) that the neutral flag covers enemy goods[347] with the exception
of contraband of war, (3) that neutral goods, contraband of war
excepted, are not liable to capture under the enemy flag, (4) that
blockades, in order to be binding, must be effective, which means
maintained by a force sufficient really to prevent access to the coast
of the enemy. Since, with the exception of a few States such as the
United States of America, Colombia, Venezuela, Bolivia, and
Uruguay, all members of the Family of Nations are now parties to the
Declaration of Paris, it may well be maintained that the rules quoted
are general International Law, the more so as the non-signatory
Powers have hitherto in practice always acted in accordance with
those rules.[348]
[346] See Martens, N.R.G. XV. p. 767, and above, vol. I. § 559.
[347] It has been asserted—see, for instance, Rivier, II. p. 429—that the neutral flag
covers only private, not public, enemy property, and therefore that such goods on neutral
vessels as belong to the State of the enemy may be seized and appropriated. This
opinion would seem, however, to be untenable in face of the fact that the Declaration of
Paris speaks of marchandise neutre without any qualification, only excepting contraband
goods, thus protecting the whole of the cargo under the neutral flag, contraband
excepted. See below, § 319, p. 385, note 3.
[348] That there is an agitation for the abolition of the Declaration of Paris has been
mentioned above, § 83, p. 100, note 3.

The Principle of Appropriation of Private Enemy Vessels and Enemy Goods thereon.
§ 178. The Declaration of Paris did not touch upon the old rule
that private enemy vessels and private enemy goods thereon may be
seized and appropriated, and this rule is, therefore, as valid as ever,
although there is much agitation for its abolition. In 1785 Prussia
and the United States of America had already stipulated by article 23
of their Treaty of Friendship[349] that in case of war between the
parties each other's merchantmen shall not be seized and
appropriated. Again, in 1871 the United States and Italy, by article
12 of their Treaty of Commerce,[350] stipulated that in case of war
between the parties each other's merchantmen, with the exception
of those carrying contraband of war or attempting to break a
blockade, shall not be seized and appropriated. In 1823 the United
States had already made the proposal to Great Britain, France, and
Russia[351] for a treaty abrogating the rule that enemy merchantmen
and enemy goods thereon may be appropriated; but Russia alone
accepted the proposal under the condition that all other naval
Powers should consent. Again, in 1856,[352] on the occasion of the
Declaration of Paris, the United States endeavoured to obtain the
victory of the principle that enemy merchantmen shall not be
appropriated, making it a condition of their accession to the
Declaration of Paris that this principle should be recognised. But
again the attempt failed, owing to the opposition of Great Britain.
[349] See Martens, R. IV. p. 37. Perels (p. 198) maintains that this article has not been
adopted by the Treaty of Commerce between Prussia and the United States of May 1,
1828; but this statement is incorrect, for article 12 of this treaty—see Martens, N.R. VII.
p. 615—adopts it expressly.
[350] See Martens, N.R.G. 2nd Ser. I. p. 57.
[351] See Wharton, III. § 342, pp. 260-261, and Moore, VII. § 1198, p. 465.
[352] See Wharton, III. § 342, pp. 270-287, and Moore, VII. § 1198, p. 466.
At the outbreak of war in 1866, Prussia and Austria expressly
declared that they would not seize and appropriate each other's
merchantmen. At the outbreak of the Franco-German War in 1870,
Germany declared French merchantmen exempt from capture, but
she changed her attitude when France did not act upon the same
lines. It should also be mentioned that already in 1865 Italy, by
article 211 of her Marine Code, enacted that, in case of war with any
other State, enemy merchantmen not carrying contraband of war or
breaking a blockade shall not be seized and appropriated, provided
reciprocity be granted. And it should further be mentioned that the
United States of America made attempts[353] in vain to secure
immunity from capture to enemy merchantmen and goods on sea at
the First as well as at the Second Hague Peace Conference.
[353]See Holls, The Peace Conference at the Hague, pp. 306-321, and Scott,
Conferences, pp. 699-707.
It cannot be denied that the constant agitation, since the middle
of the eighteenth century, in favour of the abolition of the rule that
private enemy vessels and goods may be captured on the High Seas,
might, during the second half of the nineteenth century, have met
with success but for the decided opposition of Great Britain. Public
opinion in Great Britain was not, and is not, prepared to consent to
the abolition of this rule. And there is no doubt that the abolition of
the rule would involve a certain amount of danger to a country like
Great Britain whose position and power depend chiefly upon her
navy. The possibility of annihilating an enemy's commerce by
annihilating his merchant fleet is a powerful weapon in the hands of
a great naval Power. Moreover, if enemy merchantmen are not
captured, they can be fitted out as cruisers, or at least be made use
of for the transport of troops, munitions, and provisions. Have not
several maritime States made arrangements with their steamship
companies to secure the building of their Transatlantic liners
according to plans which make these merchantmen easily
convertible into men-of-war?
The argument that it is unjust that private enemy citizens should
suffer through having their property seized has no weight in face of
the probability that fear of the annihilation of its merchant fleet in
case of war may well deter a State intending to go to war from
doing so. It is a matter for politicians, not for jurists, to decide
whether Great Britain must in the interest of self-preservation
oppose the abolition of the rule that sea-borne private enemy
property may be confiscated.
However this may be, since the end of the nineteenth century it
has not been the attitude of Great Britain alone which stands in the
way of the abolition of the rule. Since the growth of navies among
continental Powers, these Powers have learnt to appreciate the value
of the rule in war, and the outcry against the capture of
merchantmen has become less loud. To-day, it may perhaps be said
that, even if Great Britain were to propose the abolition of the rule,
it is probable that a greater number of the maritime States would
refuse to accede. For it should be noted that at the Second Peace
Conference, France, Russia, Japan, Spain, Portugal, Mexico,
Colombia, and Panama, besides Great Britain, voted against the
abolition of the rule. And there is noticeable a slow, but constant,
increase in the number of continental publicists[354] who oppose the
abolition of the once so much objected to practice of capturing
enemy merchantmen.
[354] See, for instance, Perels, § 36, pp. 195-198; Röpcke, Das Seebeuterecht (1904),
pp. 36-47; Dupuis, Nos. 29-31; Pillet, p. 119; Giordana, La proprieta privata nelle guerre
maritime, etc. (1907); Niemeyer, Prinzipien des Seekriegsrechts (1909); Boidin, pp. 144-
167. On the other hand, the Institute of International Law has several times voted in
favour of the abolition of the rule; see Tableau Général de l'Institut de droit International
(1893), pp. 190-193. The literature concerning the question of confiscation of private
enemy property on sea is abundant. The following authors, besides those already quoted
above at the commencement of § 173, may be mentioned:—Upton, The Law of Nations
affecting Commerce during War (1863); Cauchy, Du respect de la propriété privée dans
la guerre maritime (1866); Vidari, Del rispetto della proprietà privata fra gli stati in
guerra (1867); Gessner, Zur Reform des Kriegsseerechts (1875); Klobukowski, Die
Seebeute oder das feindliche Privateigenthum zur See (1877); Bluntschli, Das Beuterecht
im Kriege und das Seebeuterecht insbesondere (1878); Boeck, De la propriété privée
ennemie sous pavillon ennemi (1882); Dupuis, La guerre maritime et les doctrines
anglaises (1899); Leroy, La guerre maritime (1900); Röpcke, Das Seebeuterecht (1904);
Hirst, Commerce and Property in Naval Warfare: A Letter of the Lord Chancellor (1906);
Hamman, Der Streit um das Seebeuterecht (1907); Wehberg, Das Beuterecht im Land
und Seekrieg (1909); Cohen, The Immunity of Enemy's Property from Capture at Sea
(1909); Macdonell, Some plain Reasons for Immunity from Capture of Private Property at
Sea (1910). See also the literature quoted by Bonfils, No. 1281, Pradier-Fodéré, VIII.
Nos. 3070-3090, and Boeck, Nos. 382-572, where the arguments of the authors against
and in favour of the present practice are discussed.

Impending Codification of Law of Sea Warfare.


§ 179. Be that as it may, the time is not very far distant when the
Powers will perforce come to an agreement on this as on other
points of sea warfare, in a code of regulations regarding sea warfare
as a pendant to the Hague Regulations regarding warfare on land.
An initiative step was taken by the United States of America by her
Naval War Code[355] published in 1900, although she withdrew[356] the
Code in 1904. Meanwhile, the Second Peace Conference has
produced a number of Conventions dealing with some parts of Sea
Warfare, namely: (1) the Convention (VI.) concerning the status of
enemy merchantmen at the outbreak of hostilities; (2) the
Convention (VII.) concerning the conversion of merchantmen into
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

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


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

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


personal growth every day!

ebookbell.com

You might also like