100% found this document useful (1 vote)
81 views48 pages

Python Programming An Introduction To Computer Science John M. Zelle Instant Download

The document is a PDF download link for the book 'Python Programming: An Introduction to Computer Science' by John M. Zelle, published in 2003. It includes a comprehensive table of contents covering various topics in computer science and programming, specifically using Python. Additional links to related computer science textbooks are also provided.

Uploaded by

swhppxuam1491
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
100% found this document useful (1 vote)
81 views48 pages

Python Programming An Introduction To Computer Science John M. Zelle Instant Download

The document is a PDF download link for the book 'Python Programming: An Introduction to Computer Science' by John M. Zelle, published in 2003. It includes a comprehensive table of contents covering various topics in computer science and programming, specifically using Python. Additional links to related computer science textbooks are also provided.

Uploaded by

swhppxuam1491
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/ 48

Python Programming An Introduction to Computer

Science John M. Zelle - PDF Download (2025)

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

Visit ebookultra.com today to download the complete set of


ebooks or textbooks
Here are some recommended products for you. Click the link to
download, or explore more at ebookultra.com

The Art Science of Java an introduction to computer


science 1st Edition Eric Roberts

https://ebookultra.com/download/the-art-science-of-java-an-
introduction-to-computer-science-1st-edition-eric-roberts/

Quantum Computer Science An Introduction 1st Edition N.


David Mermin

https://ebookultra.com/download/quantum-computer-science-an-
introduction-1st-edition-n-david-mermin/

Hack Audio An Introduction to Computer Programming and


Digital Signal Processing in MATLAB 2019th Edition Eric
Tarr
https://ebookultra.com/download/hack-audio-an-introduction-to-
computer-programming-and-digital-signal-processing-in-matlab-2019th-
edition-eric-tarr/

Basic Computation and Principles of Computer Programming


An Introduction to Computing WBUT 2015 4th Edition E.
Balagurusamy
https://ebookultra.com/download/basic-computation-and-principles-of-
computer-programming-an-introduction-to-computing-wbut-2015-4th-
edition-e-balagurusamy/
Introduction to Computing and Programming in Python a
Multimedia Approach Mark J. Guzdial

https://ebookultra.com/download/introduction-to-computing-and-
programming-in-python-a-multimedia-approach-mark-j-guzdial/

Systematic Theology An Introduction to Christian Belief


1st Edition John M. Frame

https://ebookultra.com/download/systematic-theology-an-introduction-
to-christian-belief-1st-edition-john-m-frame/

Introduction to Programming with Java 3rd Edition John


Dean

https://ebookultra.com/download/introduction-to-programming-with-
java-3rd-edition-john-dean/

Introduction to Python for Science and Engineering Second


Edition David J. Pine

https://ebookultra.com/download/introduction-to-python-for-science-
and-engineering-second-edition-david-j-pine/

A Computer Science Tapestry Exploring Programming and


Computer Science with C 2nd edition Owen L. Astrachan

https://ebookultra.com/download/a-computer-science-tapestry-exploring-
programming-and-computer-science-with-c-2nd-edition-owen-l-astrachan/
Python Programming An Introduction to Computer
Science John M. Zelle Digital Instant Download
Author(s): John M. Zelle
ISBN(s): 9781887902991, 1887902996
Edition: Pap/Cdr
File Details: PDF, 1.20 MB
Year: 2003
Language: english
Python Programming:
An Introduction to Computer Science

John M. Zelle, Ph.D.

Version 1.0rc2
Fall 2002
Copyright c 2002 by John M. Zelle

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior
written permission of the author.

This document was prepared with LATEX 2ε and reproduced by Wartburg College Printing Services.
Contents

1 Computers and Programs 1


1.1 The Universal Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Program Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 What is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Hardware Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 The Magic of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Inside a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.8 Chaos and Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.9 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

2 Writing Simple Programs 13


2.1 The Software Development Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Example Program: Temperature Converter . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Elements of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.1 Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.3.2 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.4 Output Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.5 Assignment Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.1 Simple Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.5.2 Assigning Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.5.3 Simultaneous Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.6 Definite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
2.7 Example Program: Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
2.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

3 Computing with Numbers 25


3.1 Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.2 Using the Math Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
3.3 Accumulating Results: Factorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
3.4 The Limits of Int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.5 Handling Large Numbers: Long Ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.6 Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

4 Computing with Strings 39


4.1 The String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.2 Simple String Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.3 Strings and Secret Codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3.1 String Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3.2 Programming an Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.3.3 Programming a Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3.4 Other String Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

i
ii CONTENTS

4.3.5 From Encoding to Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48


4.4 Output as String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.4.1 Converting Numbers to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.4.2 String Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.4.3 Better Change Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.5 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.5.1 Multi-Line Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.5.2 File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.5.3 Example Program: Batch Usernames . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.5.4 Coming Attraction: Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
4.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5 Objects and Graphics 61


5.1 The Object of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
5.2 Graphics Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
5.3 Using Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.4 Graphing Future Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.5 Choosing Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.6 Interactive Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.6.1 Getting Mouse Clicks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.6.2 Handling Textual Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.7 Graphics Module Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.1 GraphWin Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.2 Graphics Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.7.3 Entry Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.7.4 Displaying Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.7.5 Generating Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.8 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

6 Defining Functions 85
6.1 The Function of Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
6.2 Functions, Informally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 Future Value with a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
6.4 Functions and Parameters: The Gory Details . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.5 Functions that Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
6.6 Functions and Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

7 Control Structures, Part 1 101


7.1 Simple Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.1.1 Example: Temperature Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
7.1.2 Forming Simple Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
7.1.3 Example: Conditional Program Execution . . . . . . . . . . . . . . . . . . . . . . . 104
7.2 Two-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
7.3 Multi-Way Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
7.4 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
7.5 Study in Design: Max of Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.5.1 Strategy 1: Compare Each to All . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
7.5.2 Strategy 2: Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.5.3 Strategy 3: Sequential Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.5.4 Strategy 4: Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.5.5 Some Lessons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
7.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
CONTENTS iii

8 Control Structures, Part 2 119


8.1 For Loops: A Quick Review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
8.2 Indefinite Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
8.3 Common Loop Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.3.1 Interactive Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
8.3.2 Sentinel Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
8.3.3 File Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.3.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.4 Computing with Booleans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4.1 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4.2 Boolean Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
8.5 Other Common Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.5.1 Post-Test Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
8.5.2 Loop and a Half . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.5.3 Boolean Expressions as Decisions . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
8.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134

9 Simulation and Design 137


9.1 Simulating Racquetball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.1.1 A Simulation Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
9.1.2 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.2 Random Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
9.3 Top-Down Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.3.1 Top-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.3.2 Separation of Concerns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
9.3.3 Second-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
9.3.4 Designing simNGames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
9.3.5 Third-Level Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.3.6 Finishing Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
9.3.7 Summary of the Design Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4 Bottom-Up Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4.1 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
9.4.2 Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
9.5 Other Design Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
9.5.1 Prototyping and Spiral Development . . . . . . . . . . . . . . . . . . . . . . . . . . 150
9.5.2 The Art of Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
9.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

10 Defining Classes 155


10.1 Quick Review of Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
10.2 Example Program: Cannonball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.2 Designing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.2.3 Modularizing the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3 Defining New Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3.1 Example: Multi-Sided Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
10.3.2 Example: The Projectile Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
10.4 Objects and Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.4.1 Encapsulating Useful Abstractions . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.4.2 Putting Classes in Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.5 Widget Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.1 Example Program: Dice Roller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.2 Building Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
10.5.3 Building Dice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
iv CONTENTS

10.5.4 The Main Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172


10.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

11 Data Collections 177


11.1 Example Problem: Simple Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
11.2 Applying Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
11.2.1 Lists are Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
11.2.2 Lists vs. Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
11.2.3 List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
11.3 Statistics with Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
11.4 Combining Lists and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
11.5 Case Study: Python Calculator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.1 A Calculator as an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.2 Constructing the Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
11.5.3 Processing Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
11.6 Non-Sequential Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
11.6.1 Dictionary Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
11.6.2 Dictionary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
11.6.3 Example Program: Word Frequency . . . . . . . . . . . . . . . . . . . . . . . . . . 194
11.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

12 Object-Oriented Design 201


12.1 The Process of OOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
12.2 Case Study: Racquetball Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
12.2.1 Candidate Objects and Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
12.2.2 Implementing SimStats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
12.2.3 Implementing RBallGame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
12.2.4 Implementing Player . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
12.2.5 The Complete Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
12.3 Case Study: Dice Poker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.1 Program Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.2 Identifying Candidate Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
12.3.3 Implementing the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
12.3.4 A Text-Based UI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
12.3.5 Developing a GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
12.4 OO Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
12.4.1 Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
12.4.2 Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.4.3 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
12.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

13 Algorithm Analysis and Design 225


13.1 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
13.1.1 A Simple Searching Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
13.1.2 Strategy 1: Linear Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
13.1.3 Strategy 2: Binary Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
13.1.4 Comparing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
13.2 Recursive Problem-Solving . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
13.2.1 Recursive Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
13.2.2 Recursive Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
13.2.3 Recursive Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
13.3 Sorting Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
13.3.1 Naive Sorting: Selection Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
13.3.2 Divide and Conquer: Merge Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
CONTENTS v

13.3.3 Comparing Sorts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234


13.4 Hard Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
13.4.1 Towers of Hanoi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
13.4.2 The Halting Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
13.4.3 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
vi CONTENTS
Chapter 1

Computers and Programs

Almost everyone has used a computer at one time or another. Perhaps you have played computer games or
used a computer to write a paper or balance your checkbook. Computers are used to predict the weather,
design airplanes, make movies, run businesses, perform financial transactions, and control factories.
Have you ever stopped to wonder what exactly a computer is? How can one device perform so many
different tasks? These basic questions are the starting point for learning about computers and computer
programming.

1.1 The Universal Machine


A modern computer might be defined as “a machine that stores and manipulates information under the con-
trol of a changeable program.” There are two key elements to this definition. The first is that computers
are devices for manipulating information. This means that we can put information into a computer, and it
can transform the information into new, useful forms, and then output or display the information for our
interpretation.
Computers are not the only machines that manipulate information. When you use a simple calculator to
add up a column of numbers, you are entering information (the numbers) and the calculator is processing the
information to compute a running sum which is then displayed. Another simple example is a gas pump. As
you fill your tank, the pump uses certain inputs: the current price of gas per gallon and signals from a sensor
that reads the rate of gas flowing into your car. The pump transforms this input into information about how
much gas you took and how much money you owe.
We would not consider either the calculator or the gas pump as full-fledged computers, although modern
versions of these devices may actually contain embedded computers. They are different from computers in
that they are built to perform a single, specific task. This is where the second part of our definition comes into
the picture: computers operate under the control of a changeable program. What exactly does this mean?
A computer program is a detailed, step-by-step set of instructions telling a computer exactly what to do.
If we change the program, then the computer performs a different sequence of actions, and hence, performs
a different task. It is this flexibility that allows your PC to be at one moment a word processor, at the next
moment a financial planner, and later on, an arcade game. The machine stays the same, but the program
controlling the machine changes.
Every computer is just a machine for executing (carrying out) programs. There are many different kinds
of computers. You might be familiar with Macintoshes and PCs, but there are literally thousands of other
kinds of computers both real and theoretical. One of the remarkable discoveries of computer science is
the realization that all of these different computers have the same power; with suitable programming, each
computer can basically do all the things that any other computer can do. In this sense, the PC that you might
have sitting on your desk is really a universal machine. It can do anything you want it to, provided you can
describe the task to be accomplished in sufficient detail. Now that’s a powerful machine!

1
2 CHAPTER 1. COMPUTERS AND PROGRAMS

1.2 Program Power


You have already learned an important lesson of computing: Software (programs) rules the hardware (the
physical machine). It is the software that determines what any computer can do. Without programs, comput-
ers would just be expensive paperweights. The process of creating software is called programming, and that
is the main focus of this book.
Computer programming is a challenging activity. Good programming requires an ability to see the big
picture while paying attention to minute detail. Not everyone has the talent to become a first-class program-
mer, just as not everyone has the skills to be a professional athlete. However, virtually anyone can learn how
to program computers. With some patience and effort on your part, this book will help you to become a
programmer.
There are lots of good reasons to learn programming. Programming is a fundamental part of computer
science and is, therefore, important to anyone interested in becoming a computer professional. But others can
also benefit from the experience. Computers have become a commonplace tool in our society. Understanding
the strengths and limitations of this tool requires an understanding of programming. Non-programmers often
feel they are slaves of their computers. Programmers, however, are truly the masters. If you want to become
a more intelligent user of computers, then this book is for you.
Programming can also be loads of fun. It is an intellectually engaging activity that allows people to
express themselves through useful and sometimes remarkably beautiful creations. Believe it or not, many
people actually write computer programs as a hobby. Programming also develops valuable problem-solving
skills, especially the ability to analyze complex systems by reducing them to interactions of understandable
subsystems.
As you probably know, programmers are in great demand. More than a few liberal arts majors have turned
a couple computer programming classes into a lucrative career option. Computers are so commonplace in the
business world today that the ability to understand and program computers might just give you the edge over
your competition, regardless of your occupation.

1.3 What is Computer Science?


You might be surprised to learn that computer science is not the study of computers. A famous computer
scientist named Edsgar Dijkstra once quipped that computers are to computer science what telescopes are to
astronomy. The computer is an important tool in computer science, but it is not itself the object of study.
Since a computer can carry out any process that we can describe, the real question is What processes can we
describe? Put another way, the fundamental question of computer science is simply What can be computed?
Computer scientists use numerous techniques of investigation to answer this question. The three main ones
are design, analysis, and experimentation.
One way to demonstrate that a particular problem can be solved is to actually design a solution. That is,
we develop a step-by-step process for achieving the desired result. Computer scientists call this an algorithm.
That’s a fancy word that basically means “recipe.” The design of algorithms is one of the most important
facets of computer science. In this book you will find techniques for designing and implementing algorithms.
One weakness of design is that it can only answer the question What is computable? in the positive. If I
can devise an algorithm, then the problem is solvable. However, failing to find an algorithm does not mean
that a problem is unsolvable. It may mean that I’m just not smart enough, or I haven’t hit upon the right idea
yet. This is where analysis comes in.
Analysis is the process of examining algorithms and problems mathematically. Computer scientists have
shown that some seemingly simple problems are not solvable by any algorithm. Other problems are in-
tractable. The algorithms that solve these problems take too long or require too much memory to be of
practical value. Analysis of algorithms is an important part of computer science; throughout this book we
will touch on some of the fundamental principles. Chapter 13 has examples of unsolvable and intractable
problems.
Some problems are too complex or ill-defined to lend themselves to analysis. In such cases, computer
scientists rely on experimentation; they actually implement systems and then study the resulting behavior.
Even when theoretical analysis is done, experimentation is often needed in order to verify and refine the
1.4. HARDWARE BASICS 3

Output Devices
CPU

Input Devices

Secondary
Main Memory
Memory

Figure 1.1: Functional View of a Computer.

analysis. For most problems, the bottom-line is whether a working, reliable system can be built. Often we
require empirical testing of the system to determine that this bottom-line has been met. As you begin writing
your own programs, you will get plenty of opportunities to observe your solutions in action.

1.4 Hardware Basics

You don’t have to know all the details of how a computer works to be a successful programmer, but under-
standing the underlying principles will help you master the steps we go through to put our programs into
action. It’s a bit like driving a car. Knowing a little about internal combustion engines helps to explain why
you have to do things like fill the gas tank, start the engine, step on the accelerator, etc. You could learn
to drive by just memorizing what to do, but a little more knowledge makes the whole process much more
understandable. Let’s take a moment to “look under the hood” of your computer.
Although different computers can vary significantly in specific details, at a higher level all modern digital
computers are remarkably similar. Figure 1.1 shows a functional view of a computer. The central processing
unit (CPU) is the “brain” of the machine. This is where all the basic operations of the computer are carried
out. The CPU can perform simple arithmetic operations like adding two numbers and can also do logical
operations like testing to see if two numbers are equal.
The memory stores programs and data. The CPU can only directly access information that is stored in
main memory (called RAM for Random Access Memory). Main memory is fast, but it is also volatile. That is,
when the power is turned off, the information in the memory is lost. Thus, there must also be some secondary
memory that provides more permanent storage. In a modern personal computer, this is usually some sort of
magnetic medium such as a hard disk (also called a hard drive) or floppy.
Humans interact with the computer through input and output devices. You are probably familiar with
common devices such as a keyboard, mouse, and monitor (video screen). Information from input devices is
processed by the CPU and may be shuffled off to the main or secondary memory. Similarly, when information
needs to be displayed, the CPU sends it to one or more output devices.
So what happens when you fire up your favorite game or word processing program? First, the instructions
that comprise the program are copied from the (more) permanent secondary memory into the main memory
of the computer. Once the instructions are loaded, the CPU starts executing the program.
Technically the CPU follows a process called the fetch execute cycle. The first instruction is retrieved
from memory, decoded to figure out what it represents, and the appropriate action carried out. Then the next
instruction is fetched, decoded and executed. The cycle continues, instruction after instruction. This is really
all the computer does from the time that you turn it on until you turn it off again: fetch, decode, execute. It
doesn’t seem very exciting, does it? But the computer can execute this stream of simple instructions with
blazing speed, zipping through millions of instructions each second. Put enough simple instructions together
in just the right way, and the computer does amazing things.
4 CHAPTER 1. COMPUTERS AND PROGRAMS

1.5 Programming Languages


Remember that a program is just a sequence of instructions telling a computer what to do. Obviously, we
need to provide those instructions in a language that a computer can understand. It would be nice if we could
just tell a computer what to do using our native language, like they do in science fiction movies. (“Computer,
how long will it take to reach planet Alphalpha at maximum warp?”) Unfortunately, despite the continuing
efforts of many top-flight computer scientists (including your author), designing a computer to understand
human language is still an unsolved problem.
Even if computers could understand us, human languages are not very well suited for describing complex
algorithms. Natural language is fraught with ambiguity and imprecision. For example, if I say: “I saw the
man in the park with the telescope,” did I have the telescope, or did the man? And who was in the park? We
understand each other most of the time only because all humans share a vast store of common knowledge and
experience. Even then, miscommunication is commonplace.
Computer scientists have gotten around this problem by designing notations for expressing computa-
tions in an exact, and unambiguous way. These special notations are called programming languages. Every
structure in a programming language has a precise form (its syntax) and a precise meaning (its semantics). A
programming language is something like a code for writing down the instructions that a computer will follow.
In fact, programmers often refer to their programs as computer code, and the process of writing an algorithm
in a programming language is called coding.
Python is one example of a programming language. It is the language that we will use throughout this
book. You may have heard of some other languages, such as C++, Java, Perl, Scheme, or BASIC. Although
these languages differ in many details, they all share the property of having well-defined, unambiguous syntax
and semantics.
All of the languages mentioned above are examples of high-level computer languages. Although they are
precise, they are designed to be used and understood by humans. Strictly speaking, computer hardware can
only understand very low-level language known as machine language.
Suppose we want the computer to add two numbers. The instructions that the CPU actually carries out
might be something like this.

load the number from memory location 2001 into the CPU
load the number from memory location 2002 into the CPU
Add the two numbers in the CPU
store the result into location 2003

This seems like a lot of work to add two numbers, doesn’t it? Actually, it’s even more complicated than this
because the instructions and numbers are represented in binary notation (as sequences of 0s and 1s).
In a high-level language like Python, the addition of two numbers can be expressed more naturally: c =
a + b. That’s a lot easier for us to understand, but we need some way to translate the high-level language
into the machine language that the computer can execute. There are two ways to do this: a high-level language
can either be compiled or interpreted.
A compiler is a complex computer program that takes another program written in a high-level language
and translates it into an equivalent program in the machine language of some computer. Figure 1.2 shows
a block diagram of the compiling process. The high-level program is called source code, and the resulting
machine code is a program that the computer can directly execute. The dashed line in the diagram represents
the execution of the machine code.
An interpreter is a program that simulates a computer that understands a high-level language. Rather than
translating the source program into a machine language equivalent, the interpreter analyzes and executes the
source code instruction by instruction as necessary. Figure 1.3 illustrates the process.
The difference between interpreting and compiling is that compiling is a one-shot translation; once a
program is compiled, it may be run over and over again without further need for the compiler or the source
code. In the interpreted case, the interpreter and the source are needed every time the program runs. Compiled
programs tend to be faster, since the translation is done once and for all, but interpreted languages lend
themselves to a more flexible programming environment as programs can be developed and run interactively.
The translation process highlights another advantage that high-level languages have over machine lan-
guage: portability. The machine language of a computer is created by the designers of the particular CPU.
1.6. THE MAGIC OF PYTHON 5

Source
Code Compiler Machine
(Program) Code

Running
Outputs
Inputs Program

Figure 1.2: Compiling a High-Level Language

Source
Code Computer
(Program)
Running an
Outputs
Interpreter
Inputs

Figure 1.3: Interpreting a High-Level Language.

Each kind of computer has its own machine language. A program for a Pentium CPU won’t run on a Mac-
intosh that sports a PowerPC. On the other hand, a program written in a high-level language can be run on
many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another
program). For example, if I design a new computer, I can also program a Python interpreter for it, and then
any program written in Python can be run on my new computer, as is.

1.6 The Magic of Python


Now that you have all the technical details, it’s time to start having fun with Python. The ultimate goal is
to make the computer do our bidding. To this end, we will write programs that control the computational
processes inside the machine. You have already seen that there is no magic in this process, but in some ways
programming feels like magic.
The computational processes inside the computer are like magical spirits that we can harness for our
work. Unfortunately, those spirits only understand a very arcane language that we do not know. What we
need is a friendly Genie that can direct the spirits to fulfill our wishes. Our Genie is a Python interpreter. We
can give instructions to the Python interpreter, and it directs the underlying spirits to carry out our demands.
We communicate with the Genie through a special language of spells and incantations (i.e., Python). The
best way to start learning about Python is to let our Genie out of the bottle and try some spells.
You can start the Python interpreter in an interactive mode and type in some commands to see what
happens. When you first start the interpreter program, you may see something like the following:

Python 2.1 (#1, Jun 21 2001, 11:39:00)


[GCC pgcc-2.91.66 19990314 (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
>>>

The  is a Python prompt indicating that the Genie is waiting for us to give it a command. In programming
languages, a complete command is called a statement.
Here is a sample interaction with the Python interpreter.
6 CHAPTER 1. COMPUTERS AND PROGRAMS

>>> print "Hello, World"


Hello, World
>>> print 2 + 3
5
>>> print "2 + 3 =", 2 + 3
2 + 3 = 5

Here I have tried out three examples using the Python print statement. The first statement asks Python to
display the literal phrase Hello, World. Python responds on the next line by printing the phrase. The second
print statement asks Python to print the sum of 2 and 3. The third print combines these two ideas.
Python prints the part in quotes “2 + 3 =” followed by the result of adding 2 + 3, which is 5.
This kind of interaction is a great way to try out new things in Python. Snippets of interactive sessions
are sprinkled throughout this book. When you see the Python prompt  in an example, that should tip
you off that an interactive session is being illustrated. It’s a good idea to fire up Python and try the examples
for yourself.
Usually we want to move beyond snippets and execute an entire sequence of statements. Python lets us
put a sequence of statements together to create a brand-new command called a function. Here is an example
of creating a new function called hello.

>>> def hello():


print "Hello"
print "Computers are Fun"

>>>

The first line tells Python that we are defining a new function called hello. The following lines are indented
to show that they are part of the hello function. The blank line (obtained by hitting the <Enter> key
twice) lets Python know that the definition is finished, and the interpreter responds with another prompt.
Notice that the definition did not cause anything to happen. We have told Python what should happen when
the hello function is used as a command; we haven’t actually asked Python to perform it yet.
A function is invoked by typing its name. Here’s what happens when we use our hello command.

>>> hello()
Hello
Computers are Fun
>>>

Do you see what this does? The two print statements from the hello function are executed in sequence.
You may be wondering about the parentheses in the definition and use of hello. Commands can have
changeable parts called parameters that are placed within the parentheses. Let’s look at an example of a
customized greeting using a parameter. First the definition:

>>> def greet(person):


print "Hello", person
print "How are you?"

Now we can use our customized greeting.

>>> greet("John")
Hello John
How are you?
>>> greet("Emily")
Hello Emily
How are you?
>>>
1.6. THE MAGIC OF PYTHON 7

Can you see what is happening here? When we use greet we can send different names to customize the
result. We will discuss parameters in detail later on. For the time being, our functions will not use parameters,
so the parentheses will be empty, but you still need to include them when defining and using functions.
One problem with entering functions interactively at the Python prompt like this is that the definitions go
away when we quit Python. If we want to use them again the next time, we have to type them all over again.
Programs are usually created by typing definitions into a separate file called a module or script. This file is
saved on a disk so that it can be used over and over again.
A module file is just a text file, and you can create one using any program for editing text, like a notepad or
word processor program (provided you save your program as a “plain text” file). A special type of program
known as a programming environment simplifies the process. A programming environment is specifically
designed to help programmers write programs and includes features such as automatic indenting, color high-
lighting, and interactive development. The standard Python distribution includes a programming environment
called Idle that you may use for working on the programs in this book.
Let’s illustrate the use of a module file by writing and running a complete program. Our program will
illustrate a mathematical concept known as chaos. Here is the program as we would type it into Idle or some
other editor and save in a module file:
# File: chaos.py
# A simple program illustrating chaotic behavior.

def main():
print "This program illustrates a chaotic function"
x = input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1 - x)
print x

main()
This file should be saved with with the name chaos.py. The .py extension indicates that this is a
Python module. You can see that this particular example contains lines to define a new function called main.
(Programs are often placed in a function called main.) The last line of the file is the command to invoke
this function. Don’t worry if you don’t understand what main actually does; we will discuss it in the next
section. The point here is that once we have a program in a module file, we can run it any time we want.
This program can be run in a number of different ways that depend on the actual operating system and
programming environment that you are using. If you are using a windowing system, you can run a Python
program by (double-)clicking on the module file’s icon. In a command-line situation, you might type a
command like python chaos.py. If you are using Idle (or another programming environment) you can
run a program by opening it in the editor and then selecting a command like import, run, or execute.
One method that should always work is to start the Python interpreter and then import the file. Here is
how that looks.
>>> import chaos
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>>
8 CHAPTER 1. COMPUTERS AND PROGRAMS

Typing the first line import chaos tells the Python interpreter to load the chaos module from the file
chaos.py into main memory. Notice that I did not include the .py extension on the import line; Python
assumes the module will have a .py extension.
As Python imports the module file, each line executes. It’s just as if we had typed them one-by-one at the
interactive Python prompt. The def in the module causes Python to create the main function. When Python
encounters the last line of the module, the main function is invoked, thus running our program. The running
program asks the user to enter a number between 0 and 1 (in this case, I typed “.25”) and then prints out a
series of 10 numbers.
When you first import a module file in this way, Python creates a companion file with a .pyc extension.
In this example, Python creates another file on the disk called chaos.pyc. This is an intermediate file used
by the Python interpreter. Technically, Python uses a hybrid compiling/interpreting process. The Python
source in the module file is compiled into more primitive instructions called byte code. This byte code (the
.pyc) file is then interpreted. Having a .pyc file available makes importing a module faster the second time
around. However, you may delete the byte code files if you wish to save disk space; Python will automatically
re-create them as needed.
A module only needs to be imported into a session once. After the module has been loaded, we can run the
program again by asking Python to execute the main command. We do this by using a special dot notation.
Typing chaos.main() tells Python to invoke the main function in the chaos module. Continuing with
our example, here is how it looks when we rerun the program with 26 as the input.

>>> chaos.main()
Enter a number between 0 and 1: .26
0.75036
0.73054749456
0.767706625733
0.6954993339
0.825942040734
0.560670965721
0.960644232282
0.147446875935
0.490254549376
0.974629602149
>>>

1.7 Inside a Python Program


The output from the chaos program may not look very exciting, but it illustrates a very interesting phe-
nomenon known to physicists and mathematicians. Let’s take a look at this program line by line and see what
it does. Don’t worry about understanding every detail right away; we will be returning to all of these ideas in
the next chapter.
The first two lines of the program start with the # character:

# File: chaos.py
# A simple program illustrating chaotic behavior.

These lines are called comments. They are intended for human readers of the program and are ignored by
Python. The Python interpreter always skips any text from the pound sign (#) through the end of a line.
The next line of the program begins the definition of a function called main.

def main():

Strictly speaking, it would not be necessary to create a main function. Since the lines of a module are
executed as they are loaded, we could have written our program without this definition. That is, the module
could have looked like this:
1.7. INSIDE A PYTHON PROGRAM 9

# File: chaos.py
# A simple program illustrating chaotic behavior.

print "This program illustrates a chaotic function"


x = input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1 - x)
print x
This version is a bit shorter, but it is customary to place the instructions that comprise a program inside of a
function called main. One immediate benefit of this approach was illustrated above; it allows us to (re)run
the program by simply invoking chaos.main(). We don’t have to reload the module from the file in order
to run it again, which would be necessary in the main-less case.
The first line inside of main is really the beginning of our program.
print "This program illustrates a chaotic function"
This line causes Python to print a message introducing the program when it runs.
Take a look at the next line of the program.
x = input("Enter a number between 0 and 1: ")
Here x is an example of a variable. A variable is used to give a name to a value so that we can refer to it at
other points in the program. The entire line is an input statement. When Python gets to this statement, it
displays the quoted message Enter a number between 0 and 1: and then pauses, waiting for the
user to type something on the keyboard and press the <Enter> key. The value that the user types is then
stored as the variable x. In the first example shown above, the user entered .25, which becomes the value of
x.
The next statement is an example of a loop.
for i in range(10):
A loop is a device that tells Python to do the same thing over and over again. This particular loop says to
do something 10 times. The lines indented underneath the loop heading are the statements that are done 10
times. These form the body of the loop.
x = 3.9 * x * (1 - x)
print x
The effect of the loop is exactly the same as if we had written the body of the loop 10 times:
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
print x
x = 3.9 * x * (1 - x)
10 CHAPTER 1. COMPUTERS AND PROGRAMS

print x
x = 3.9 * x * (1 - x)
print x

Obviously using the loop instead saves the programmer a lot of trouble.
But what exactly do these statements do? The first one performs a calculation.

x = 3.9 * x * (1 - x)

This is called an assignment statement. The part on the right side of the = is a mathematical expression.
Python uses the * character to indicate multiplication. Recall that the value of x is 0 25 (from the input
statement). The computed value is 3 9 0 25 1 0 25 or 0 73125. Once the value on the righthand side is
  

computed, it is stored back (or assigned) into the variable that appears on the lefthand side of the =, in this
case x. The new value of x (0 73125) replaces the old value (0 25).
The second line in the loop body is a type of statement we have encountered before, a print statement.

print x

When Python executes this statement the current value of x is displayed on the screen. So, the first number
of output is 0.73125.
Remember the loop executes 10 times. After printing the value of x, the two statements of the loop are
executed again.

x = 3.9 * x * (1 - x)
print x

Of course, now x has the value 0 73125, so the formula computes a new value of x as 3 9 0 73125 1  

0 73125 , which is 0 76644140625.




Can you see how the current value of x is used to compute a new value each time around the loop? That’s
where the numbers in the example run came from. You might try working through the steps of the program
yourself for a different input value (say 0 5). Then run the program using Python and see how well you did
impersonating a computer.

1.8 Chaos and Computers


I said above that the chaos program illustrates an interesting phenomenon. What could be interesting about
a screen full of numbers? If you try out the program for yourself, you’ll find that, no matter what number
you start with, the results are always similar: the program spits back 10 seemingly random numbers between
0 and 1. As the program runs, the value of x seems to jump around, well, chaotically.
The function computed by this program has the general form: k x 1 x , where k in this case is 3.9.
  

This is called a logistic function. It models certain kinds of unstable electronic circuits and is also sometimes
used to predict population under limiting conditions. Repeated application of the logistic function can pro-
duce chaos. Although our program has a well defined underlying behavior, the output seems unpredictable.
An interesting property of chaotic functions is that very small differences in the initial value can lead to
large differences in the result as the formula is repeatedly applied. You can see this in the chaos program by
entering numbers that differ by only a small amount. Here is the output from a modified program that shows
the results for initial values of 0 25 and 0 26 side by side.

input 0.25 0.26


---------------------------
0.731250 0.750360
0.766441 0.730547
0.698135 0.767707
0.821896 0.695499
0.570894 0.825942
0.955399 0.560671
1.9. EXERCISES 11

0.166187 0.960644
0.540418 0.147447
0.968629 0.490255
0.118509 0.974630

With very similar starting values, the outputs stay similar for a few iterations, but then differ markedly. By
about the fifth iteration, there no longer seems to be any relationship between the two models.
These two features of our chaos program, apparent unpredictability and extreme sensitivity to initial
values, are the hallmarks of chaotic behavior. Chaos has important implications for computer science. It
turns out that many phenomena in the real world that we might like to model and predict with our computers
exhibit just this kind of chaotic behavior. You may have heard of the so-called butterfly effect. Computer
models that are used to simulate and predict weather patterns are so sensitive that the effect of a single
butterfly flapping its wings in New Jersey might make the difference of whether or not rain is predicted in
Peoria.
It’s very possible that even with perfect computer modeling, we might never be able to measure existing
weather conditions accurately enough to predict weather more than a few days in advance. The measurements
simply can’t be precise enough to make the predictions accurate over a longer time frame.
As you can see, this small program has a valuable lesson to teach users of computers. As amazing as
computers are, the results that they give us are only as useful as the mathematical models on which the
programs are based. Computers can give incorrect results because of errors in programs, but even correct
programs may produce erroneous results if the models are wrong or the initial inputs are not accurate enough.

1.9 Exercises
1. Compare and contrast the following pairs of concepts from the chapter.

(a) Hardware vs. Software


(b) Algorithm vs. Program
(c) Programming Language vs. Natural Language
(d) High-Level Language vs. Machine Language
(e) Interpreter vs. Compiler
(f) Syntax vs. Semantics

2. List and explain in your own words the role of each of the five basic functional units of a computer
depicted in Figure 1.1.

3. Write a detailed algorithm for making a peanut butter and jelly sandwich (or some other simple every-
day activity).

4. As you will learn in a later chapter, many of the numbers stored in a computer are not exact values, but
rather close approximations. For example, the value 0.1, might be stored as 0.10000000000000000555.
Usually, such small differences are not a problem; however, given what you have learned about chaotic
behavior in Chapter 1, you should realize the need for caution in certain situations. Can you think of
examples where this might be a problem? Explain.

5. Trace through the Chaos program from Section 1.6 by hand using 0 15 as the input value. Show the
sequence of output that results.

6. Enter and run the Chaos program from Section 1.6 using whatever Python implementation you have
available. Try it out with various values of input to see that it functions as described in the chapter.

7. Modify the Chaos program from Section 1.6 using 2.0 in place of 3.9 as the multiplier in the logistic
function. Your modified line of code should look like this:
12 CHAPTER 1. COMPUTERS AND PROGRAMS

x = 2.0 * x * (1 - x)
Run the program for various input values and compare the results to those obtained from the original
program. Write a short paragraph describing any differences that you notice in the behavior of the two
versions.
8. Modify the Chaos program from Section 1.6 so that it prints out 20 values instead of 10.
9. (Advanced) Modify the Chaos program so that it accepts two inputs and then prints a table with two
columns similar to the one shown in Section 1.8. (Note: You will probably not be able to get the
columns to line up as nicely as those in the example. Chapter 4 discusses how to print numbers with a
fixed number of decimal places.)
Other documents randomly have
different content
and unsophisticated mind. No God! I found it hard to shake off the thought
suggested by that man's expression.

The next day, when we were away from the Fort on our journey, I told my
companions. Susa's eyes fairly bulged with astonishment, and Joseph said,
"He must be without any mind," and we dismissed the subject; but as my
father thoroughly believed in God, and we were abroad to do his bidding
along the line of that faith, we tied on our snowshoes and took the straight
course for Pigeon Lake. Old Joseph now became guide. This was the scene
of his young manhood. Here he had trapped beaver (ever and anon we
crossed the creeks and saw the dams), here he had tracked and slain many a
moose and elk. In this vicinity huge grizzlies had licked the dust at the crack
of his old flintlock. Long years ago he had helped to make this small
winding trail which he now hoped to pick up and to keep to the lake. Big
fires and wonderful growth had changed the scene. More than twenty years
had elapsed since this road was frequented, but with unerring memory and
skill the old man picked up the road, and on we went slowly through the
deep snow, across bits of prairie, and while all around looked the same,
without a miss we would again enter the bush on the unused trail. It must
have taken centuries to develop a brain capable of thus having photographed
upon it the topography of a country.

Saturday night found us some seven or eight miles from the lake and in a
dense forest, with the snow about three feet deep on the level. Here we
camped for Sunday, and again I noticed Joseph's consistent Sabbatarianism,
for except for supper he never ceased to chop and pack wood until midnight,
and thus obviated our working any on the Sabbath. From early morn this
Indian had been tramping down the deep snow ahead of our trains, and
working his brain in order to pick up the old trail. He had lifted thousands of
pounds of snow in the course of the long day's travel, and now he willingly
and gladly works until midnight to provide wood for our camp, which, being
an open one, consumes a very large quantity. And all because it is written,
"Remember the Sabbath day to keep it holy." I do not know what my readers
will think about this, but I do know what I thought at the time, and it was
this: I would undergo hardship and danger with such a man beside me a
great deal rather than live in the same house in comfort and plenty with the
man who a few days since said to me, "I do not believe there is a God."
We spent the Sabbath quietly, and early Monday morning continued our
way, reaching the site of the proposed Mission about noon. Here we found
the cache Oliver and I had made, still secure, but surrounded with the tracks
of a wolverine, who thus far had been baffled. Into this cache we put the
balance of the provisions we had brought, and making it doubly secure, as
we thought, placed the plough on top, and then retraced our steps back to the
camp we had left in the morning. From this we reached Edmonton Tuesday
night, and were home early Thursday afternoon.

CHAPTER IV.
Epidemic breaks out among the Indians—Snow-blindness—I take to me a wife—Our
modest dowry—My father officiates as a Stationing Committee—Fearful mortality
among the Indians—Our journey to Pigeon Lake—The epidemic attacks our camp—A
rude hospital—An exciting buffalo hunt—Chased by a maddened bull—Narrow
escape.

At Edmonton we heard an epidemic was raging among the southern


Indians, and that many were dying. As to the nature of the disease or
particulars concerning it we had no information. But even the rumor of its
approach was startling, for in the absence of any Government or other
quarantine regulations and with tribal war existing this disease would soon
cover the whole country with its ravages. In the meantime, as the season was
advancing, we redoubled our efforts to bring in supplies. To do this we had
to travel largely at night, the March sun making it too warm for our dogs in
the daytime. This night-work with the strong glare of the bright snow was
exceedingly hard on the eyes. Many a poor fellow became snow-blind, and
the pain of this was excruciating. Fortunately for myself, my eyes were
never affected; but it made me feel miserable to witness so much suffering
and be helpless to give relief.
The Indians as a preventive would blacken their faces with charcoal or
damped powder, but as nearly all the natives had dark eyes, they were most
susceptible to snow-blindness. My experience was that those with lighter
colored eyes were generally free from this dreaded malady.

Old Joseph, Susa and myself made a number of quick trips to and from
different camps during these March days and nights; and about the end of
the month we gave this up for the season. Then it came to pass that I put into
execution a project I had been contemplating for some time and that was to
take unto me a wife. My bride to be was the daughter of the Rev. H. B.
Steinhauer. I had met her in the autumn of 1862, when I accompanied father
on his first visit to Whitefish Lake. Our acquaintance, which had grown into
a courtship on my part, was now between two and three years old. Our
parents willingly gave us their consent and blessing. Father and Peter
accompanied us to Whitefish Lake, and father married us in the presence of
my wife's parents and people. Our "honeymoon trip" was to drive from
Whitefish Lake to Victoria with dog-train, when the season was breaking up,
and in consequence the trip was a hard one. Then after a short sojourn at
Victoria we set out for the purpose of establishing the new Mission at Pigeon
Lake, father having signified his strong desire that such should be done,
notwithstanding that the Board of Missions had not as yet either consented to
or approved of such a course. But father was thoroughly impressed with the
wisdom and necessity of such action, and finally told me I ought to go and
begin work out there; and, said he, "You can live where any man can." Of
course I was proud to have father think this of me. His knowledge of the
work required, and his confidence in my ability to do this work, more than
made up to me at the time for the fact that there was not a dollar of
appropriation from the Missionary Society. But father gave us a pair of four-
point Hudson's Bay blankets, two hundred ball and powder, and some net
twine, together with his confidence and blessing; to which in all things
mother said, "Amen."

In the meantime the epidemic we had heard rumors of came to us, and
proved to be a dangerous combination of measles and scarlet fever. Among
the Black feet and the southern tribes hundreds had died, and already the
mortality was large among the northern Crees. From camp to camp the
disease spread. As winter still lingered and the deep snow was again turning
into water on the plains and in the woods, these lawless, roving people
without quarantine protection, lacking the means of keeping dry or warm,
and altogether destitute of medicine or medical help, became an easy prey to
the epidemic.

Already many lodges of sick folk were camped close to the Mission, and
others were coming in every day. Father and mother and Peter had their
hands full in attending to the sick, ministering to the dying, and burying the
dead. And as this was a white man's disease, there were plenty of the wilder
Indians to magnify the wrongs these Indians were submitting to at the hands
of the whites. Some of them were exceedingly impudent and ugly to deal
with; indeed, if it were not for Maskepetoon and his own people, many a
time our Mission party would have suffered. As it was life was constantly in
danger. Men and women crazed and frenzied because of disease and death
were beside us night and day. Nevertheless father said "Go," and we started
from among such scenes on our journey to Pigeon Lake.

Father had loaned us two oxen and carts for the trip. I had some eight or
ten ponies, about all I had to show for five years' work; but as I had been
helpful to father in educating my brother and sister in Ontario, I was thankful
I had come off as well as I did. A great part of the way was under water. The
streams were full, but on we rode and rolled and rafted and forded.

Our party consisted of my wife and self, Oliver, a young Indian, Paul by
name, and his wife. Our provisions were buffalo meat, fresh and dry and in
pemmican. We had five bushels of potatoes with us, but these were saved for
the purpose of starting the new Mission. I purposed having every Indian who
might come to me begin a garden, and these potatoes were for seed, and
should not be eaten. Paul and I supplemented our larders by hunting. Ducks
and geese, chickens and rabbits saved the dried provisions and proved very
good fare.

We scouted carefully across and past those paths and roads converging
from the plains and south country to Fort Edmonton. Not until we had made
sure, so far as we could, that the enemy was not just then in the vicinity, did
we venture our party across these highways of the lawless tribes. Then
passing Edmonton we struck out south-westward, into a country wherein as
yet no carts or waggons had ever rolled; and now it kept Paul and myself
busy hunting and clearing the way, while Oliver and the women brought up
the carts and loose horses. Our progress was slow and tedious, but we were
working for the future as well as the present.

When up here in the winter I concluded that we could on the first trip
with carts take them to within some twenty-five miles of the lake to which
we were going. Working along as best we could, Saturday night found us at
this limit, and as we were very tired, and the weather was fine, we merely
covered our carts, made an open fire in front, and thus prepared to spend the
Sabbath in rest and quiet.

Because of the dense forest and brush we had come through, and also as
we were some thirty miles from Edmonton, we felt comparatively safe from
any war parties of plain Indians that might be roaming the country, as these
men were more or less afraid of the woods. Sunday was a beautiful day, but
towards evening there came a change, and during the night a furious
snowstorm set in. Monday morning there was nearly a foot of snow, and the
storm continued all day and on into Tuesday night. We kept as quiet as
possible under our humble shelter without fire or any warm food until
Wednesday morning, when the sun came out and the storm was over. Then
to our dismay Mrs. McDougall and Paul's wife were taken with the measles,
and sending Oliver to look after the stock, Paul and I sought the highest
ground in the vicinity, cleared away the snow, cut poles and put up our
leather lodge.

This we floored thickly with brush. Then we laid a brush causeway from
our carts to the lodge, and moved our sick folk into the tent. In the meantime
I had put some dried meat and pounded barley into a kettle to boil over the
fire, and as the only medicine we had was cayenne pepper, I put some of this
into the soup, and this was all we had for our sick ones. Just then Oliver
came in, having found the stock, but was complaining of a sore back and
headache. I gave him a cup of my hot soup to drink, and as he sat beside the
fire warming his wet feet and limbs and drinking the soup, I saw he was
covered with the measles. So I quietly told him to change his clothes and go
into the tent. Thus in our small party of five three were down with the
epidemic which was now universal in the North-West.

For the next five or six days Paul and I had our hands full to attend to the
sick night and day, to keep up the supply of firewood (for the nights were
cold and we consumed a great amount) and to look after the stock.

Our patients in the one-roomed buffalo-skin-walled hospital were very


sick, and as we had no medicine to speak of, and nothing in the way of
dainties to tempt their appetite, often caused us extreme anxiety. Hard grease
pemmican, dried meat, or pounded meat and grease are all right when one is
strong and well, but it was more than we could do to cook or fix these up for
sick folk. When we could Paul and I took it in turn to seek for ducks and
chickens to make broth with, but there were very few of these to be found
near to us, and it was not until the fever abated that, by leaving wood and
water ready and making our patients as comfortable as possible, we went
farther afield for game, and were successful in finding ducks and geese and
the eggs of wild-fowl as our reward.

It was on one of these hunts, and while our sick people were steadily
convalescing, that we came upon the fresh tracks of a buffalo bull. As we
thought he might provide good meat we determined to follow him up. I think
we had kept his track steadily for three hours, when all of a sudden my
sleigh dogs, whom I had left as I thought secure at camp, came up to us on
the jump, and now took the lead on the track, and very soon were at the bull,
as we knew from their furious barking. We rode as fast as we could in the
soft ground and through the dense bush, and presently galloped out on an old
beaver-meadow. Sure enough the dogs had the bull at bay, and the old fellow
as soon as we came in sight charged straight at us. As there was an opening
into another part of the meadow I thought he was making for that, so sat my
horse, gun in hand, ready to shoot him as he passed. But this was not in the
bull's programme. He was in for a fight, and putting down his head came
right at me. My horse knew what that meant, for he already had been gored
by a mad bull, and the little fellow did not wait for a second dose, but
bounded on as fast as he could. My gun was a single-barrelled, muzzle-
loading shot-gun, and though I had a ball in, I did not care to risk my one
shot under such circumstances. In fact I very soon had all I could do to sit on
my horse, keep my gun, and save my head from being broken; for in a few
bounds we were across the meadow and into the woods, where, the ground
being soft, my horse was hard pressed by the big fellow, who was crashing
along at his heels. Fortunately "Scarred Thigh," as the Indians called him,
was no ordinary cayuse, but strong and quite speedy. Yet owing to soft
ground and brush the bull seemed to be gaining on us at several times. Paul
afterwards told me he was so close to me as to raise my pony's tail with his
horn, but could not come nearer to his much desired victims.

I knew that my horse could not, sinking as he was at every jump into the
soft ground, keep this gait up much longer, and because of the trees and
brush I had no chance to shoot back at the bull. I was momentarily expecting
to feel him hoisting us, when I spied a thick cluster of big poplars just ahead.
Now, I thought, if we can dodge behind these we may gain time on our
enemy. So I urged on my noble beast, and as if to help us, just as I pulled
him around the clump of poplars, a projecting limb knocked my cap off. This
falling right in the face of the bull for the moment blinded him, and with an
angry snort he went thundering past as I pulled behind the trees.
"My cap ... falling right in the face of the bull, for the moment blinded
him."

"That was close," said Paul, who was following up as fast as his pony
would bring him; "if he had been a bear he would have bitten your horse, but
every time he put his head down to toss you, your horse left him that much."
I jumped from my horse and patted his neck, rubbed his nose, and felt
thankful for our escape. Then we tied our animals in the shelter of the large
trees, and followed after the bull on foot, for in such ground and such timber
we were much safer on foot than on horseback.

Already our dogs had again brought the bull to bay, as we could hear, and
approaching with caution we soon saw him fighting desperately. Alert as we
were he heard us coming and again charged, but we met him with two balls,
and the old fellow staggered back to the middle of a swamp of ice and snow-
water and fell dead.

"That fellow had a bad heart, or he would not have gone out into the
middle of a pond of water to die," said Paul; and it was cold enough work
skinning and butchering him, with the ice-water up to our knees. But those
were the days when stockings and boots and rubbers were beyond our reach
in more ways than one. However, the meat was good and a providential
supply to us and our sick folk. Moreover, our dogs needed an extra feed, and
they got it.

It was late in the day when two heavily laden horses and two tired men
came in sight of camp, and it was as good medicine to Oliver, who saw us
approaching and noted the fresh meat with a smile all over his gaunt and
pale face, for the disease had wofully thinned the poor fellow. Only those
who have been in such circumstances can truly appreciate the relief
experienced by our sorely-tried party.

CHAPTER V.
Our caravan moves on—Difficulties of packing—Oliver's adventure with a buffalo—Novel
method of "blazing" a path—Arrival at Pigeon Lake—House-building—Abundance of
fish—Indians camp about the Mission—I form many enduring friendships—Indians
taught fishing with nets.
Now that our people were convalescing we began to make ready for a
fresh start, this time without carts. Everything had to be packed on the backs
of our oxen and horses, entailing no small amount of work on the part of
Paul and myself. As the ground was everywhere wet, I was afraid to run the
risk of a relapse with any of our patients, and would not let them step off the
brush flooring we had placed to keep them out of the water. The distance we
had to travel to bring us to the lake was about twenty-five miles, and we
purposed making it in two days. Our sick folk would find twelve miles far
enough for one day, and our thin and weak horses would also find the
distance sufficient.

Paul and I had two oxen and eight horses to saddle and pack with sick
folk and tent and bedding and all our household stuff, and while we did not
seem to be possessed of much of anything, yet it was quite a problem to
arrange all on the backs of those ten animals. Sometimes while we were
fastening the one pack on, three or four of our horses would lie down with
their loads, and in thus getting down and up disorganize the whole work.

We put our wives on the strongest and quietest horses, and placed Oliver
on a quiet but very hungry Blackfoot cayuse, giving him our guns to carry in
addition to his own. Thus we set out along the almost obliterated bridle-path
which I had gone over but once and that in the winter time when the snow
was deep, and which neither Paul nor Oliver had as yet seen. My memory
was sorely taxed to make out the trail where there was open country to pass
through. In single file and with slow and solemn steps our sick people rode
their steeds, while our horses labored under the burdens of their weak packs.
Paul and I were kept busy arranging these packs, for as our saddles were
crude and our binding material rawhide, this would stretch, and the saddles
or packs become loose, so that we were kept rushing from one to the other of
our transports. This made progress so slow that it did seem as if even the
twelve miles we hoped to cover would prove too much for the long spring
day. But notwithstanding all the worrying and the work we had some fun as
well. During the afternoon, while we were behind the rest fixing up a pack
on one of the horses, I heard Oliver in a greatly excited voice shouting,
"John! John! Hurry—come quick!" I sprang away to the front, and found
that our train was crossing a small bit of prairie, and from one end of it, and
coming out of the woods, there was a buffalo bull charging right straight for
Oliver.
My dogs were worrying the big fellow, but it was Oliver who demanded
my attention. He had our three guns on the saddle before him, but seemingly
never thinking of them, he kept shouting to me to "shoot the bull." In his
excitement he had let go his bridle, and this had fallen on the ground, while
his hungry horse was intent on cropping grass and would not budge from the
spot. In vain Oliver kicked and shouted; what cared that Blackfoot pony for
the charge of a buffalo? He was accustomed to this, and moreover was
hungry, and here was grass, and so far as he was concerned all else might
"go to grass." Not so philosophic, however, was his rider. He was all
excitement. With a big muffler wrapped around his face, a blanket around
his body and legs, and our three guns in his arms, he kept shouting
vehemently for "John." As I ran, not even the possibility of the bull hurting
some of us could keep me from laughing.

Oliver dared not jump from his horse into the water that surrounded us,
for I had threatened him all manner of punishment if he got wet and ran the
risk of a relapse, and he was in mortal fear of the huge bull that was now
coming quite close to him. But as I ran up, and before I could reach for my
gun from Oliver, the brute took away in another direction, thus happily
relieving the situation. He evidently was, as Paul put it, "a good-hearted
fellow," and as we had all we could very well manage, we did not fire any
shots after him. But this excitement and fun helped to break the monotony of
our journey.

It was late when we reached a point that I thought would be half way to
the lake, and we hurriedly cut brush for our patients to alight on, and
unsaddled the oxen and horses. I had put the whole of our seed potatoes on
my saddle horse, "Scarred Thigh," and he had behaved extremely well all the
day, carrying his load without a jar or disarrangement, as if he instinctively
knew we had enough trouble with the rest. But now he insisted on my taking
the load from him before I should relieve the others. As soon as I went to a
horse to unpack him the little fellow would step in between me and the other
horse, and plainly say by his actions that his was the first claim, so all our
party said, "Help him first, he deserves it." To unsaddle the ten animals and
unpack seven of them, to cut lodge-poles and erect the lodge and floor it
with brush, to chop firewood and cook supper kept Paul and I on the jump
until late, but our patients though tired were gaining strength and appetite,
and we were thankful.
The next day was a repetition of the one just described, only more so—
water deeper, timber denser, and creeks multiplying. My wife and I each had
an old-fashioned Hudson's Bay trunk. One was painted blue and the other
red, and we packed these on the biggest of the oxen, firmly securing them by
the handles before and behind, with collar straps and breeching of harness;
and now as these boxes rubbed alternately on the trees on either side of the
narrow path, one could track them by the paint, this side red and the other
blue, which often was a source of wonder to travellers who came later along
this path.

When we came nearer the lake we were glad to find that the land around
the lake, being higher than that over which we had come, was comparatively
dry, and that spring was further advanced than anywhere else along our
route. Thankful for this, we put up our skin lodge near the place where we
proposed to build our house.

We were not the first in the same line on this spot. Nearly twenty years
before Benjamin Sinclair, a native lay agent, under the direction of the Rev.
R. Rundle, began a Mission, but the coming into the vicinity of a party of
Blackfeet, and their killing of some of the people, had created a stampede
from here to Lac la Biche, some two hundred miles north-east, and this place
was abandoned.

The little clearing had well-nigh grown up again, and with the exception
of the lake in front we were surrounded with dense forests. The surrounding
country was altogether more like my native land than any other spot I had
seen in the North-West. The lake was approximately some five by eighteen
miles in size, and full of fish—too full of the whitefish for these to be of
good quality. But just now we could not test them, as the ice was in such
condition that it was not safe to attempt to set a net under it. There was
nothing to do but to wait until it melted before attempting any fishing.

Our first work was to put up a house. Humble though it might be, we
hoped to make it better than the "smoking skin lodge." As we had most of
the logs on the ground, we were not long in raising the shanty. It was another
thing, however, to whip-saw the lumber for flooring, etc. The building of the
chimney, too, was altogether a new experience to me; and when I had built
this to the proper height, I was terribly disgusted to have it smoke worse than
the lodge did. But I soon saw my mistake, and pulling the greater portion
down began anew on a different plan, which proved a great success.

One morning bright and early Providence sent us a deer. Paul took his
gun and went towards the lake to get, as I thought, a shot at some ducks. But
it was a deer he had seen, and soon he had it secured, for which we were
very thankful, as our stock of fresh meat was now low. But what is the meat
of a small deer to the eating capacity of five healthy people—especially
those of our party who were now fairly over the epidemic? When you are on
the one diet, and that wild meat, the consumption thereof is rather startling.
In the meantime the ice melted, and we made a raft, set a net and caught
some poor whitefish. We caught plenty of pike and suckers, too, and to
ourselves and dogs these were a wholesome change.

The first Indians to come to us were some pagans, having with them two
genuine old conjurers, whose drums and rattles and medicine songs were
thum-thumming and yah-yahing almost all the time they stayed with us. As
some of the older members of this camp, and nearly all the younger ones,
came to our services, which we held every evening and three times on
Sunday, these "high priests of this old faith" renewed their efforts, if one
might judge by the noise they made; but do what they would they could not
keep their young people from our meetings. After a time a larger camp came
to us, nearly all of whom were Mountain Stonies and mostly Christian or
semi-Christian in adherence, and our gatherings became very much more
interesting. But as all of these people had the measles or were convalescing
from the epidemic, and had lost many friends because of the fearful
mortality which this caused, we were hard worked in attending to the sick
and in comforting the bereaved. As to the former, Providence smiled upon
us, and all of our patients, young and old, recovered, which helped us in our
first acquaintance and gave us the beginning of an influence which grew
with the years.

Here I first met many who became my warm friends and bosom
companions around many a camp-fire and on many a hunting field, when
danger and darkness and hunger and storm alternated with peace and
sunlight and plenty and calm. Here was great big Adam, who from being a
first-class Pharisee, with demeanor a voicing of "Lord, I thank Thee," etc.,
became, through the instrumentality of a hymn I taught him to sing, humbled
and penitent, and sought forgiveness and light. He found it; and oh, how
changed he became! And there was his son Jacob, one of the grandest men I
have known, for whom both nature and grace had done great things. When I
first saw him he was recovering from the prevailing scourge. A noble fellow
he was in form and feature. He had a big record as a moose-hunter, and was
famed as a long distance runner. As he spoke both Stony and Cree fluently, I
very soon saw he was a man to be cultivated and made useful for God and
country.

Then there was "Little Beaver," a Southern Mountain Stony, who very
soon let me know that while he was glad to see me, he could never make up
his mind to live down here in the woods and lowlands, but was always
sighing for the mountains and foot-hills of his own section of the country,
and who by his descriptions made me wish to start west with him and view
for myself the land he loved. Another genuine character was "Has-no-hole-
in-his-ear," an old man with a large family of boys who became my allies
and faithful friends. The father was an ardent Christian in his way, and
thoroughly loyal to the new Mission and the young missionary.

Later there came in a camp of Crees, amongst whom was Samson, then in
his prime as a hunter, and who afterwards became the successor of
Maskepetoon as chief of the wood Crees. Samson and I soon found that we
were congenial spirits, and our warm friendship continues to this day. There
was also Paul Chian, a French mixed blood, who had grown up amongst the
Indians, and was one of them in everything but appearance. He had been a
noted gambler and warrior, and the blood of men was on his hands; but he
had found that the blood of Christ is efficacious to the cleansing from sin,
and he became a splendid character, a solid man, a class leader and a local
preacher, always in his place, and a "genuine stand-by." And there were
many good women in these camps who became our staunch friends, and in
whose lodges we received true hospitality and many real evidences of a solid
appreciation of our work and message.

These various people came and went at short intervals. I suppose during
our stay at Pigeon Lake for about two months that spring of 1865 no camp of
Indians remained longer than two weeks at a time. Until I provided them
with nets they had none. Indeed, some of the plain and wood Indians did not
know how to set a net, much less how to make or mend one. To provide
twine and teach them to make nets was an undertaking that took time to
accomplish. Then to live in one place very long was a hardship in itself to
these nomads of wood and plain, while to live on fish alone would be foolish
to them so long as buffalo were on the plains or moose and elk in the woods.
No matter as to time in the obtaining of these animals. The days and months
might come and go—these men did not value time; that appreciation is an
evolution belonging to a permanent or settled life.

CHAPTER VI.
We are visited by a band of Crees—Our guests steal away with a bunch of horses—Stonies
set out in hot pursuit—Little William's strategy—Horses recaptured—We begin
farming operations—Arrival of Mr. Steinhauer—Home to Victoria again—A
memorable Sabbath—My gun bursts—Narrow escape—My mother's cares and
anxieties—Home-made furniture.

While we were building our house, and during the stay of the Stonies
with us, a small war party of Crees came to our little settlement on their way
(so they said) to the Blackfoot country. As they knew me they came to our
lodge, and all went well the first day and night; but during the second night
they stole out of our lodge, took a bunch of the Stonies' horses and put for
home. Awakened by their retreating footsteps, I roused Paul and we struck a
light and found our guests were gone, Then we ran down to the path leading
eastward, and lighting some matches found the tracks of the horses.
Immediately we aroused

CHAPTER VII.
I travel with Maskepetoon's camp—Effects of environment on the Indians—Nature's
grandeur and beauty—Degradation through paganism—The noble Chief Maskepetoon
—Indian councils—On the fringe of the buffalo herds—Indian boy lost—A false
conjurer—The lad recovered.

Maskepetoon's camp had now been gone about two weeks, and my
instructions were to accompany this camp for part of the summer in its
movements, and to do what I could towards the Christianizing of the people.
Accordingly, taking Paul with me, and leaving our wives and Oliver with
mother, we started for the big camp. We took two oxen and carts and several
horses, as father had made arrangements with Muddy Bull to make dried
provisions for home use. Our course was down the valley of the Vermilion,
and then out through the hilly country that runs by Birch Lake to Battle
River.

We killed several moulting geese as we travelled, and enjoyed them as


food. On our fourth day out we came up to the camp, and turning the oxen
and carts over to Muddy Bull, we domiciled ourselves in his lodge, and at
once became part of this moving town. My work was all around me. Here
was paganism intensely conservative, the outcome of many centuries of
tradition. And here were its high priests, and the novitiate following which
thronged after them, seeming to me as "the blind leading the blinder," if this
were possible; the whole causing a devolution which was lowering the range
of thought and life and ideal, and all the while producing a profundity of
ignorance as to things moral and spiritual which in turn, as a logical
sequence, affected the physical and material life of this people.

Doubtless environment has a great deal to do with the formation of


character and being, but in the environment of these men, outside of buffalo
and tribal communism, I failed to find anything that might be thought
degenerating in its tendencies. The great herds of buffalo as abused by man
were hurtful to himself, and therefore in the fulness of time the Great Father,
in the interests of His children, wiped them from the face of the earth. Tribal
communism has always been hurtful to individuality, and without this no
race of men can progress. But apart from these factors in the life of this
people, the rest of their environment was, in my judgment, of the nature and
kind to help them, and to give them large, broad and fine views of life and
all things. Why, then, this degradation witnessed on every hand? This intense
superstition and ignorance, to my mind, is all due to the faith and religion of
this people. Their faith is a dead one; no wonder they are dead in trespasses
and sins. We believe we are now coming to them with a living faith, but even
then we require infinite patience. The change will come, no doubt, but
when? O Lord, Thou alone knowest when.

To come back to environment. So far as nature's realm affected the


sojourners in this part of the valley of the Saskatchewan, these should be
among the best of men. Beauty and wealth and power and a mighty purpose
are apparent on every hand. These hundreds of miles of territory, these
millions of acres of rich grass and richer soil, these hundreds of days of
glorious sunshine in every year, these countless millions of cubic feet of
healthful atmosphere, surcharged with ozone so that one ever and anon feels
like "taking the wings of the morning"—what a splendid heritage!

Look at this delightful spot where we are encamped for the day. It is now
nearing the midsummer, and the hills and valleys are clothed in the richest
verdure. Take note of these hills and valleys. Behold the shapeliness of
yonder range of hills, and the sweep of this vale at your feet. See the
exquisite carvings of this ascent, and the beautiful rounding of that summit.
Drink in the wonderful symmetry displayed in planting those islands of
timber. Behold as yon fleecy cloud comes between the sun and the scene of
sylvan beauty, how the whole is hallowed and mellowed by the shading of
light! Think of the corrosions of ice and the cleansings of flood necessary to
create such a variety of hill and dale as this. Ponder over the ages of later
development, and calculate the layers of vegetable matter needed to make
this wealthy soil and produce this infinite variety of flora and herb and forest
and grass. Now to my mind all this is exceedingly helpful, and every time I
look upon such environment I am made a better and stronger man. Then why
not all men be thus helped and made better? All?—there it is, our faiths are
not alike. Even a wrong faith is mighty to the pulling down of "strongholds,"
and man under such influences descends.

But even here there are exceptions, and environment has its way in a
measure. Amongst these men and women you will come across those who
are big and broad and grand and noble. Blessed be the Lord for this! And one
of these latter even now is calling to me and speaking in broken English,
"John Mak-e-doo-gal-un, come here now," with big emphasis on the "now,"
and I readily recognize the voice and walk over to the lodge of the old Chief
Maskepetoon.

"So you have come, John? I asked your father to let you come with my
camp for a few weeks. There is plenty for you to do, my boy. But I called
you just now, as my tent is empty, to tell you that I am sorry and ashamed
that my son was with those young rascals who tried to steal horses from the
Stonies at Pigeon Lake.

"I told him that under the circumstances I could not have done anything if
he and his party had been killed: that he must remember that all men were
now my friends, and especially all missionaries, and if I ever fought again it
would be on the side of the missionary. That he should have gone from your
lodge to steal the horses of your people made me much ashamed and sorry in
my heart. I told your father about it, and he said the young men were foolish
to act in that way towards you—that you were the Indians' friend; and I
believe that, and I want you to work hard, and will pray the Great Spirit to
help you to gain a power over young men."

I thanked the old Chief for his confidence, and told him I should always
expect his advice and help in my work. Then I gave him my news, and he
told me what the camp's movements were to be, and that there was to be an
immense gathering of several camps for the holding of the annual festival
and "Thirst Dance" of the pagan Indians. He also told me that the buffalo
were coming northward and westward, and we should move slowly to give
them a chance to come in; that the plain Crees who were coming up country
to join us were behind the herd of buffalo; and further informed me that the
peace was effectually broken on both sides, and we might expect more or
less trouble all summer.

I sat and chatted with the Chief and had supper in his lodge, and then
arranged for an evening service in the open camp. These services elicited
much interest. Paul, who was a good singer and a fine young fellow, would
take his stand by my side. Then as we sang the people gathered, and our
service would begin. I would take advantage of our surroundings or the
occurrences of the day in the selection of my subject, and then call upon our
old Chief or some one of our native Christians to lead in prayer.
In the meantime warriors and hunters on horseback and on foot and
curious women and children with "tattooed" and painted faces would come
around and watch and listen, but with native courtesy keep silence and act
orderly and seem interested.

Thus day after day we publicly proclaimed the Gospel and teaching of the
Master according to our ability, for I was but a child in these things myself;
and yet the Lord did not despise the day of small beginnings, but blessed us
and our work. While during the week conjuring and gambling and
heathenish riots went on in many portions of the camp, such was the respect
in which Maskepetoon was held by all these people that they desisted from
these things on the Sabbath. They even gave up hunting on that day because
he wished it. Not that he thus commanded. Oh, no; he was too much of a real
gentleman and too wise in his ideas of chieftainship to do this.

Slowly we moved out on the plains. Every day brought fresh scenes, and
steadily I was becoming acquainted with these people. Maskepetoon always
invited me to their councils, and seated beside him I listened to argument
and oratory, and beheld genuine gesticulation, natural and true. Sometimes
the Chief would ask me to tell about white men and how they conducted
matters. I would respond with a short address on government and municipal
organization, or at another time speak of civilization and some of its
wonders, or give a talk on education, and Maskepetoon would say, "Listen to
John. Although he is only a child in years he is a man in experience; he has
seen far and wide, he has gone to school, he has listened for years to that
wise man his father." Then at the closing up of these council gatherings
Maskepetoon would give judgment on what had been said, either approving
or condemning, and settle the matter in discussion in his own way, when the
Council would break up for the time.

Day after day we moved slowly out on the plains, the prairie openings
growing larger. All this time strict guard was kept, and the camp travelled,
when the country would permit of it, in several parallel lines of march. At
night scouts were sent out in every direction, and all of the horses either
tethered or hobbled up close within the circle of tents.

On every hand were scenes which acted as stimulators in the exercise of


care to most of the inhabitants of our moving village. Here had been a fight.
Yonder some one would point out where many had been killed. "This is
where the camp was when we brought in so many scalps and horses;" and as
I listened to these people I could in a measure begin to realize how
exceedingly romantic their lives had been, and how constantly the
excitement of tribal war had followed them.

One evening we were startled by the wail of a mother. Her eight-year-old


son was missing. The camp was searched and the boy not found. For two
nights and a day we remained in the one place and made diligent search; but
as we were now in the fringings of the large herds of buffalo, and the whole
country was tracked up, it was impossible to find any trace of the lad.

One old conjurer drummed all night, and said that the boy was killed,
locating the place of his death in a little valley near the line of our march the
day the boy was missed. He was so particular in his description of the place
and as to the manner in which the Blackfeet had waylaid the boy, that many
thought the old conjurer was telling the truth, and quite a number went with
the "Medicine Man" to the spot he had so vividly described. But while they
found the spot just as he had indicated, there were no traces of the lost boy,
nor yet any signs of the enemy. Needless to say, the party came back very
much disgusted with their "false prophet."

Another "sight-seer" went into his mysterious lodge, and when he came
out he said the boy was alive, that he had passed to the east of our course,
and gone on until he was bewildered, and continuing his wanderings he was
found by Indians from another camp which was now coming up country
from the east to intercept us. This was more comforting, but who could
vouch for its truth! Nevertheless this did prove true, for some three or four
days later, after we had encamped for the day, some strangers were seen
approaching, and when they were formally seated, and each had taken a few
whiffs of the big pipe, one of them deigned to open his lips and tell us that a
strange boy had been found and was now in their camp; that at first he was
quite out of his head, but after a day or two came to himself, and told them
where he came from, and the place to which our camp was heading, and thus
they had intercepted us. These couriers also told us of several other camps
which were coming up to join ours for the Thirst Dance Festival. The poor
mother was overjoyed to hear of her boy's safety, and our whole camp
rejoiced with her.
CHAPTER VIII.
The "Thirst Dance"—"Tobacco messages"—The head conjurer—"Dancing lodges"—The
rendezvous—The "idol tree"—Meeting of the head conjurer and the chief of the
warriors—An anxious moment—Building the "temple"—Self-torture, dancing and
sacrifices—The festival concluded—Romantic situation for our camp.

We now were drawing close to the spot which had been indicated by the
chief priest of the season as a desirable place for the annual religious
festival. Couriers came and went from the several camps. The excitement
intensified, and our camp was all astir in anticipation of meeting with the
multitudes who, like us, were making for this common ground of
appointment. I will here give my readers a brief description of this great
festival, known as

THE THIRST DANCE.

This religious gathering has been for ages an annual occurrence. It is an


occasion for the fulfilment of vows, and an opportunity for the more
religious of this pagan people to make sacrifices and to endure self-inflicted
torture and hardship in meeting the requirements of the traditional faith of
their fathers.

As the season for this approached some leading men sent "tobacco
messages" to different camps near and far, intimating that the time had come
for the annual festival, and suggesting the most desirable locality. This latter
was determined largely by the proximity of buffalo and the conditions of
tribal war.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookultra.com

You might also like