100% found this document useful (4 votes)
34 views

Buy ebook Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely cheap price

Discrete

Uploaded by

adorirturic
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 (4 votes)
34 views

Buy ebook Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely cheap price

Discrete

Uploaded by

adorirturic
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/ 61

Download Full ebookname - Read Now at ebookname.

com

Programming and Mathematical Thinking A Gentle


Introduction to Discrete Math Featuring Python 1st
Edition Allan M. Stavely

https://ebookname.com/product/programming-and-mathematical-
thinking-a-gentle-introduction-to-discrete-math-featuring-
python-1st-edition-allan-m-stavely/

OR CLICK BUTTON

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Programming in Python 3 A Complete Introduction to the


Python Language 2nd Edition Summerfield

https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/

ebookname.com

A Gentle Introduction to Optimization 1st Edition B.


Guenin

https://ebookname.com/product/a-gentle-introduction-to-
optimization-1st-edition-b-guenin/

ebookname.com

A Gentle Introduction to Stata 2018th Edition Alan C.


Acock

https://ebookname.com/product/a-gentle-introduction-to-stata-2018th-
edition-alan-c-acock/

ebookname.com

Experimental Approaches to Diabetic Retinopathy Frontiers


in Diabetes Vol 20 1st Edition H. P. Hammes

https://ebookname.com/product/experimental-approaches-to-diabetic-
retinopathy-frontiers-in-diabetes-vol-20-1st-edition-h-p-hammes/

ebookname.com
Building High Performance Business Relationships Rescue
Improve and Transform Your Most Valuable Assets 1st
Edition Tony Lendrum
https://ebookname.com/product/building-high-performance-business-
relationships-rescue-improve-and-transform-your-most-valuable-
assets-1st-edition-tony-lendrum/
ebookname.com

In Rivers Lakes and Ponds Under the Microscope 1st Edition


Sabrina Crewe

https://ebookname.com/product/in-rivers-lakes-and-ponds-under-the-
microscope-1st-edition-sabrina-crewe/

ebookname.com

Elements of set theory Enderton

https://ebookname.com/product/elements-of-set-theory-enderton/

ebookname.com

Nanomedicine Design of Particles Sensors Motors Implants


Robots and Devices Mark J. Schulz

https://ebookname.com/product/nanomedicine-design-of-particles-
sensors-motors-implants-robots-and-devices-mark-j-schulz/

ebookname.com

Israel Jordan and Palestine The Two State Imperative Asher


Susser

https://ebookname.com/product/israel-jordan-and-palestine-the-two-
state-imperative-asher-susser/

ebookname.com
The Phenomenon of Obama and the Agenda for Education Can
Hope Audaciously Trump Neoliberalism 1st Edition Paul R.
Carr
https://ebookname.com/product/the-phenomenon-of-obama-and-the-agenda-
for-education-can-hope-audaciously-trump-neoliberalism-1st-edition-
paul-r-carr/
ebookname.com
Programming and Mathematical
Thinking
A Gentle Introduction to Discrete Math
Featuring Python

Allan M. Stavely

The New Mexico Tech Press


Socorro, New Mexico, USA
Programming and Mathematical Thinking
A Gentle Introduction to Discrete Math Featuring Python
Allan M. Stavely

Copyright © 2014 Allan M. Stavely

First Edition

Content of this book available under the Creative Commons Attribution-Noncommercial-ShareAlike License. See
http://creativecommons.org/licenses/by-nc-sa/4.0/ for details.

Publisher's Cataloguing-in-Publication Data

Stavely, Allan M
Programming and mathematical thinking: a gentle introduction to discrete
math featuring Python / Allan M. Stavely.
xii, 246 p.: ill. ; 28 cm
ISBN 978-1-938159-00-8 (pbk.) — 978-1-938159-01-5 (ebook)
1. Computer science — Mathematics. 2. Mathematics — Discrete
Mathematics. 3. Python (Computer program language).

QA 76.9 .M35 .S79 2014


004-dc22

OCLC Number: 863653804

Published by The New Mexico Tech Press, a New Mexico nonprofit corporation

The New Mexico Tech Press


Socorro, New Mexico, USA
http://press.nmt.edu
Once more, to my parents, Earl and Ann

i
ii
Table of Contents
Preface ........................................................................................................ vii
1. Introduction ............................................................................................. 1
1.1. Programs, data, and mathematical objects ..................................... 1
1.2. A first look at Python .................................................................... 3
1.3. A little mathematical terminology ................................................ 10
2. An overview of Python ........................................................................... 17
2.1. Introduction ................................................................................. 17
2.2. Values, types, and names ............................................................. 18
2.3. Integers ........................................................................................ 19
2.4. Floating-point numbers ................................................................ 23
2.5. Strings .......................................................................................... 25
3. Python programs .................................................................................... 29
3.1. Statements ................................................................................... 29
3.2. Conditionals ................................................................................ 31
3.3. Iterations ..................................................................................... 35
4. Python functions ..................................................................................... 41
4.1. Function definitions ..................................................................... 41
4.2. Recursive functions ...................................................................... 43
4.3. Functions as values ...................................................................... 45
4.4. Lambda expressions ..................................................................... 48
5. Tuples ..................................................................................................... 51
5.1. Ordered pairs and n-tuples .......................................................... 51
5.2. Tuples in Python .......................................................................... 52
5.3. Files and databases ...................................................................... 54
6. Sequences ............................................................................................... 57
6.1. Properties of sequences ................................................................ 57
6.2. Monoids ...................................................................................... 59
6.3. Sequences in Python ..................................................................... 64
6.4. Higher-order sequence functions .................................................. 67
6.5. Comprehensions .......................................................................... 73
6.6. Parallel processing ....................................................................... 74
7. Streams ................................................................................................... 83
7.1. Dynamically-generated sequences ................................................ 83
7.2. Generator functions ..................................................................... 85

iii
Programming and Mathematical Thinking

7.3. Endless streams ............................................................................ 90


7.4. Concatenation of streams ............................................................ 92
7.5. Programming with streams .......................................................... 95
7.6. Distributed processing ............................................................... 103
8. Sets ....................................................................................................... 107
8.1. Mathematical sets ...................................................................... 107
8.2. Sets in Python ............................................................................ 110
8.3. A case study: finding students for jobs ....................................... 114
8.4. Flat files, sets, and tuples ........................................................... 118
8.5. Other representations of sets ...................................................... 123
9. Mappings ............................................................................................. 127
9.1. Mathematical mappings ............................................................. 127
9.2. Python dictionaries .................................................................... 131
9.3. A case study: finding given words in a file of text ...................... 135
9.4. Dictionary or function? .............................................................. 140
9.5. Multisets .................................................................................... 145
10. Relations ............................................................................................ 153
10.1. Mathematical terminology and notation .................................. 153
10.2. Representations in programs .................................................... 156
10.3. Graphs ..................................................................................... 159
10.4. Paths and transitive closure ...................................................... 164
10.5. Relational database operations ................................................ 167
11. Objects ............................................................................................... 175
11.1. Objects in programs ................................................................. 175
11.2. Defining classes ........................................................................ 177
11.3. Inheritance and the hierarchy of classes ................................... 180
11.4. Object-oriented programming .................................................. 184
11.5. A case study: moving averages ................................................. 185
11.6. Recursively-defined objects: trees ............................................. 194
11.7. State machines ......................................................................... 201
12. Larger programs ................................................................................. 213
12.1. Sharing tune lists ...................................................................... 213
12.2. Biological surveys .................................................................... 218
12.3. Note cards for writers .............................................................. 227
Afterword ................................................................................................. 233
Solutions to selected exercises ................................................................... 235
Index ........................................................................................................ 241

iv
List of Examples
1.1. Finding a name ...................................................................................... 4
1.2. Finding an email address ....................................................................... 7
1.3. Average of a collection of observations .................................................. 8
6.1. Finding a name again, in functional style ............................................. 71
6.2. Average of observations again, in functional style ................................ 72
7.1. Combinations using a generator function ............................................ 89
8.1. Finding job candidates using set operations ....................................... 117
8.2. Job candidates again, with different input files .................................. 122
9.1. Finding given words in a document ................................................... 139
9.2. A memoized function: the nth Fibonacci number ................................ 144
9.3. Number of students in each major field ............................................. 149
10.1. Distances using symmetry and reflexivity ......................................... 159
11.1. The MovingAverage class .................................................................. 191
11.2. The MovingAverage class, version 2 ................................................. 193
11.3. The Pushbutton class ....................................................................... 204
11.4. A state machine for finding fields in a string .................................... 206
11.5. Code that uses a FieldsStateMachine ............................................. 207
11.6. A state machine for finding fields, version 2 .................................... 209

v
vi
Preface
My mission in this book is to encourage programmers to think mathematically
as they develop programs.

This idea is nothing new to programmers in science and engineering fields,


because much of their work is inherently based on numerical mathematics
and the mathematics of real numbers. However, there is more to mathematics
than numbers.

Some of the mathematics that is most relevant to programming is known as


“discrete mathematics”. This is the mathematics of discrete elements, such as
symbols, character strings, truth values, and “objects” (to use a programming
term) that are collections of properties. Discrete mathematics is concerned
with such elements; collections of them, such as sets and sequences; and
connections among elements, in structures such as mappings and relations.
In many ways discrete mathematics is more relevant to programming than
numerical mathematics is: not just to particular kinds of programming, but
to all programming.

Many experienced programmers approach the design of a program by


describing its input, output, and internal data objects in the vocabulary of
discrete mathematics: sets, sequences, mappings, relations, and so on. This is
a useful habit for us, as programmers, to cultivate. It can help to clarify our
thinking about design problems; in fact, solutions often become obvious. And
we inherit a well-understood vocabulary for specifying and documenting our
programs and for discussing them with other programmers.1

For example, consider this simple programming problem. Suppose that we


are writing software to analyze web pages, and we want some code that will
read two web pages and find all of the URLs that appear in both. Some
programmers might approach the problem like this:

1
This paragraph and the example that follows are adapted from a previous book: Allan M. Stavely,
Toward Zero-Defect Programming (Reading, Mass.: Addison Wesley Longman, 1999), 142–143.

vii
First I'll read the first web page and store all the URLs I find in a list.
Then I'll read the second web page and, every time I find a URL, search
the list for it. But wait: I don't want to include the same URL in my
result more than once. I'll keep a second list of the URLs that I've
already found in both web pages, and search that before I search the
list of URLs from the first web page.

But a programmer who is accustomed to thinking in terms of discrete-


mathematical structures might immediately think of a different approach:

The URLs in a web page are a set. I'll read each web page and build
up the set of URLs in each using set insertion. Then I can get the URLs
common to both web pages by using set intersection.

Either approach will work, but the second is conceptually simpler, and it will
probably be more straightforward to implement. In fact, once the problem is
described in mathematical terms, most of the design work is already done.

That's the kind of thinking that this book promotes.

As a vehicle, I use the programming language Python. It's a clean, modern


language, and it comes with many of the mathematical structures that we will
need: strings, sets, several kinds of sequences, finite mappings (dictionaries,
which are more general than arrays), and functions that are first-class values.
All these are built into the core of the language, not add-ons implemented by
libraries as in many programming languages. Python is easy to get started
with and makes a good first language, far better than C or C++ or Java, in
my opinion. In short, Python is a good language for Getting Things Done with
a minimum of fuss. I use it frequently in my own work, and many readers will
find it sufficient for much or all of their own programming.

Mathematically, I start at a rather elementary level: the book assumes no


mathematical background beyond algebra and logarithms. In a few places I
use examples from elementary calculus, but a reader who has not studied
calculus can skip these examples. I don't assume a previous course in discrete
mathematics; I introduce concepts from discrete mathematics as I go along.
Some of these are simple but powerful concepts that (unfortunately) some

viii
programmers never learn, and we'll see how to use them to create simple and
elegant solutions to programming problems.

For example, one recurring theme in the book is the concept of a monoid. It
turns out that monoids (more than, for example, groups and semigroups) are
ubiquitous in the data types and data structures that programmers use most
often. I emphasize the extent to which all monoids behave alike and how
concepts and algorithms can be transferred from one to another.

I recommend this book for use in a first university-level course, or even an


advanced high-school course, for mathematically-oriented students who have
had some exposure to computers and programming. For students with no
such exposure, the book could be supplemented by an introductory
programming textbook, using either Python or another programming language,
or by additional lecture material or tutorials presenting techniques of
programming. Or the book could be used in a second course that is preceded
by an introductory programming course of the usual kind.

Otherwise, the ideal reader is someone who has had at least some experience
with programming, using either Python or another programming language.
In fact, I hope that some of my readers will be quite experienced programmers
who may never have been through a modern, mathematically-oriented program
of study in computer science. If you are such a person, you'll see many ideas
that will probably be new to you and that will probably improve your
programming.

At the end of most chapters is a set of exercises. Instructors can use these
exercises in laboratory sessions or as homework exercises, and some can be
used as starting points for class discussions. Many instructors will want to
supplement these exercises with their own extended programming assignments.

In a number of places I introduce a topic and then say something like “…


details are beyond the scope of this book.” The book could easily expand to
encompass most of the computer science curriculum, and I had to draw the
line somewhere. I hope that many readers, especially students, will pursue
some of these topics further, perhaps with the aid of their instructors or in
later programming and computer science classes. Some of the topics are

ix
exception handling, parallel computing, distributed computing, various
advanced data structures and algorithms, object-oriented programming, and
state machines.

Similarly, I could have included many more topics in discrete mathematics


than I did, but I had to draw the line somewhere. Some computer scientists
and mathematicians may well disagree with my choices, but I have tried to
include topics that have the most relevance to day-to-day programming. If
you are a computer science student, you will probably go on to study discrete
mathematics in more detail, and I hope that the material in this book will
show you how the mathematics is relevant to your programming work and
motivate you to take your discrete-mathematics classes more seriously.

This book is not designed to be a complete textbook or reference manual for


the Python language. The book will introduce many Python constructs, and
I'll describe them in enough detail that a reader unfamiliar with Python should
be able to understand what's going on. However, I won't attempt to define
these constructs in all their detail or to describe everything that a programmer
can do with them. I'll omit some features of Python entirely: they are more
advanced than we'll need or are otherwise outside the scope of this book.
Here are a few of them:

• some types, such as complex and byte

• some operators and many of the built-in functions and methods

• string formatting and many details of input and output

• the extensive standard library and the many other libraries that are
commonly available

• some statement types, including break and continue, and else-clauses in


while-statements and for-statements

• many variations on function parameters and arguments, including default


values and keyword parameters

• exceptions and exception handling

x
• almost all “special” attributes and methods (those whose names start and
end with a double underbar) that expose internal details of objects

• many variations on class definitions, including multiple inheritance and


decorators

Any programmer who uses Python extensively should learn about all of these
features of the language. I recommend that such a person peruse a
comprehensive Python textbook or reference manual.2

In any case, there is more to Python than I present in this book. So whenever
you think to yourself, “I see I can do x with Python — can I do y too?”, maybe
you can. Again, you can find out in a Python textbook or reference manual.

This book will describe the most modern form of Python, called Python 3. It
may be that the version of Python that you have on your computer is a version
of Python 2, such as Python 2.3 or 2.7. There are only a few differences that
you may see as you use the features of Python mentioned in this book. Here
are the most important differences (for our purposes) between Python 3 and
Python 2.7, the final and most mature version of Python 2:

• In Python 2, print is a statement type and not a function. A print statement


can contain syntax not shown in the examples in this book; however, the
syntax used in the examples — print(e) where e is a single expression —
works in both Python 2 and Python 3.

• Python 2 has a separate “long integer” type that is unbounded in size.


Conversion between plain integers and long integers (when necessary) is
largely invisible to the programmer, but long integers are (by default)
displayed with an “L” at the end. In Python 3, all integers are of the same
type, unbounded in size.

• Integer division produces an integer result in Python 2, not a floating-point


result as in Python 3.

2
As of the time of writing, comprehensive Python documentation, including the official reference
manual, can be found at http://docs.python.org.

xi
• In Python 2, characters in a string are ASCII and not Unicode by default;
there is a separate Unicode type.

Versions of Python earlier than 2.7 have more incompatibilities than these:
check the documentation for the version you use.

In the chapters that follow I usually use the author's “we” for a first-person
pronoun, but I say “I” when I am expressing my personal opinion, speaking
of my own experiences, and so on. And I follow this British punctuation
convention: punctuation is placed inside quotation marks only if it is part of
what is being quoted. Besides being more logical (in my opinion), this treatment
avoids ambiguity. For example, here's how many American style guides tell
you to punctuate:

To add one to i, you would write “i = i + 1.”

Is the “.” part of what you would write, or not? It can make a big difference,
as any programmer knows. There is no ambiguity this way:

To add one to i, you would write “i = i + 1”.

I am grateful to all the friends and colleagues who have given me help,
suggestions, and support in this writing project, most prominently Lisa
Beinhoff, Horst Clausen, Jeff Havlena, Peter Henderson, Daryl Lee, Subhashish
Mazumdar, Angelica Perry, Steve Schaffer, John Shipman, and Steve Simpson.

Finally, I am pleased to acknowledge my debt to a classic textbook: Structure


and Interpretation of Computer Programs (SICP) by Abelson and Sussman.3
I have borrowed a few ideas from it: in particular, for my treatments of higher-
order functions and streams. And I have tried to make my book a showcase
for Python much as SICP was a showcase for the Scheme language. Most
important, I have used SICP as an inspiration, a splendid example of how
programming can be taught when educators take programming seriously.

3
Harold Abelson and Gerald Jay Sussman with Julie Sussman, Structure and Interpretation of Computer
Programs (Cambridge, Mass.: The MIT Press, 1985).

xii
Chapter 1
Introduction
1.1. Programs, data, and mathematical objects
A master programmer learns to think of programs and data at many levels of
detail at different times. Sometimes the appropriate level is bits and bytes and
machine words and machine instructions. Often, though, it is far more
productive to think and work with higher-level data objects and higher-level
program constructs.

Ultimately, at the lowest level, the program code that runs on our computers
is patterns of bits in machine words. In the early days of computing, all
programmers had to work with these machine-level instructions all the time.
Now almost all programmers, almost all the time, use higher-level
programming languages and are far more productive as a result.

Similarly, at the lowest level all data in computers is represented by bits


packaged into bytes and words. Most beginning programmers learn about
these representations, and they should. But they should also learn when to
rise above machine-level representations and think in terms of higher-level
data objects.

The thesis of this book is that, very often, mathematical objects are exactly
the higher-level data objects we want. Some of these mathematical objects are
numbers, but many — the objects of discrete mathematics — are quite different,
as we will see.

So this book will present programming as done at a high level and with a
mathematical slant. Here's how we will view programs and data:

Programs will be text, in a form (which we call “syntax”) that does not look
much like sequences of machine instructions. On the contrary, our programs
will be in a higher-level programming language, whose syntax is designed for

1
Programs, data, and mathematical objects

writing, reading, and understanding by humans. We will not be much


concerned with the correspondence between programming-language constructs
and machine instructions.

The data in our programs will reside in a computer's main storage (which we
often metaphorically call “memory”) that may look like a long sequence of
machine words, but most of the time we will not be concerned with exactly
how our data objects are represented there; the data objects will look like
mathematical objects from our point of view. We assume that the main storage
is quite large, usually large enough for all the data we might want to put into
it, although not infinite in size.

We will assume that what looks simple in a program is also reasonably simple
at the level of bits and bytes and machine instructions. There will be a
straightforward correspondence between the two levels; a computer science
student or master programmer will learn how to construct implementations
of the higher-level constructs from low-level components, but from other
books than this one. We will play fair; we will not present any program
construct that hides lengthy computations or a mass of complexity in its low-
level implementation. Thus we will be able to make occasional statements
about program efficiency that may not be very specific, but that will at least
be meaningful. And you can be assured that the programming techniques that
we present will be reasonable to use in practical programs.

The language of science is mathematics; many scientists, going back to Galileo,


have said so. Equally, the language of computing is mathematics. Computer
science education teaches why and how this is so, and helps students gain
some fluency in the aspects of this language that are most relevant to them.
The current book takes a few steps in these directions by introducing some
of the concepts of discrete mathematics, by showing how useful they can be
in programming, and by encouraging programmers to think mathematically
as they do their work.

2
A first look at Python

1.2. A first look at Python


For the examples in this book, we'll use a particular programming language,
called Python. I chose Python for several reasons. It's a language that's in
common use today for producing many different kinds of software. It's
available for most computers that you're likely to use. And it's a clean and
well-designed language: for the most part, the way you express things in Python
is straightforward, with a minimum of extraneous words and punctuation. I
think you're going to enjoy using Python.

Python falls into several categories of programming language that you might
hear programmers talk about:

• It's a scripting language. This term doesn't have a precise definition, but
generally it means a language that lends itself to writing little programs
called scripts, perhaps using the kinds of commands that you might type
into a command-line window on a typical computer system. For example,
some scripts are programs that someone writes on the spur of the moment
to do simple manipulations on files or to extract data from them. Some
scripts control other programs, and system administrators often use scripting
languages to combine different functions of a computer's operating system
to perform a task. We'll see examples of Python scripts shortly. (Other
scripting languages that you might encounter are Perl and Ruby.)

• It's an object-oriented language. Object orientation is a very important


concept in programming languages. It's a rather complex concept, though,
so we'll wait to discuss it until Chapter 11. For now, let's just say that if
you're going to be working on a programming project of any size, you'll
need to know about object-oriented programming and you'll probably be
using it. (Other object-oriented languages are Java and C++.)

• It's a very high-level language, or at least it has been called that. This is
another concept that doesn't have a precise definition, but in the case of
Python it means that mathematical objects are built into the core of the
language, more so than in most other programming languages. Furthermore,
in many cases we'll be able to work with these objects in notation that

3
A first look at Python

resembles mathematical notation. We'll be exploiting these aspects of Python


throughout the book.

Depending on how you use it, Python can be a language of any of these kinds
or all of them at once.

Let's look at a few simple Python programs, to give you some idea of what
Python looks like.

The first program is the kind of very short script that a Python programmer
might write to use just once and then discard. Let's say that you have just
attended a lecture, and you met someone named John, but you can't remember
his last name. Fortunately, the lecturer has a file of the names of all the
attendees and has made that file available to you. Let's say that you have put
that file on your computer and called it “names”. There are several hundred
names in the file, so you'd like to have the computer do the searching for you.
Example 1.1 shows a Python script that will display all the lines of the file
that start with the letters “John”.

Example 1.1. Finding a name


file = open("names")
for line in file:
if line.startswith("John"):
print(line)

You may be able to guess (and guess correctly) what most of the parts of this
script do, especially if you have done any programming in another
programming language, but I'll explain the script a line at a time. Let's not
bother with the fine points, such as what the different punctuation marks
mean in Python; you'll learn all that later. For now, I'll just explain each line
in very general terms.
file = open("names")

4
A first look at Python

This line performs an operation called “opening” a file on our computer. It's
a rather complicated sequence of operations, but the general idea is this: get
a file named “names” from our computer's file system and make it available
for our program to read from. We give the name file to the result.

Here and in the other examples in this book, we won't worry about what
might happen if the open operation fails: for example, if there is no file with
the given name, or if the file can't be read for some reason. Serious Python
programmers need to learn about the features of Python that are used for
handling situations like these, and need to include code for handling
exceptional situations in most programs that do serious work.1 In a simple
one-time script like this one, though, a Python programmer probably wouldn't
bother. In any case, we'll omit all such code in our examples, simply because
that code would only distract from the points that we are trying to make.
for line in file:

This means, “For each line in file, do what comes next.” More precisely, it
means this: take each line of file, one at a time. Each time, give that line the
name line, and then do the lines of the program that come next, the lines that
are indented.
if line.startswith("John"):

This means what it appears to mean: if line starts with the letters “John”, do
what comes next.
print(line)

Since the line of the file starts with “John”, it's one that we want to see, and
this is what displays the line. On most computers, we can run the program in
a window on our computer's screen, and print will display its results in that
window.

1
The term for such code is “exception handling”, in case you want to look up the topic in Python
documentation. Handling exceptions properly can be complicated, sometimes involving difficult design
decisions, which is why we choose to treat the topic as beyond the scope of the current book.

5
A first look at Python

If you run the program, here's what you might see (depending, of course, on
what is in the file names).
John Atencio

John Atkins

Johnson Cummings

John Davis

John Hammerstein

And so on. This is pretty much as you might expect, although there may be
a couple of surprises here. Why is this output double-spaced? Well, it turns
out that each line of the file ends with a “new line” character, and the print
operation adds another. (As you learn more details of Python, you'll probably
learn how to make output like this come out single-spaced if that's what you'd
prefer.) And why is there one person here with the first name “Johnson”
instead of “John”? That shouldn't be a surprise, since our simple little program
doesn't really find first names in a line: it just looks for lines in which the first
four letters are “John”. Anyway, this output is probably good enough for a
script that you're only going to use once, especially if it reminds you that the
person you were thinking of is John Davis.

Now let's say that you'd like to get in touch with John Davis. Your luck
continues: the lecturer has provided another file containing the names and
email addresses of all the attendees. Each line of the file contains a person's
name and that person's email address, separated by a comma.

Suppose you transfer that file to your computer and give it the name “emails”.
Then Example 1.2 shows a Python script that will find and display John
Davis's email address if it's in the file.

6
A first look at Python

Example 1.2. Finding an email address


file = open("emails")
for line in file:
name, email = line.split(",")
if name == "John Davis":
print(email)

Let's look at this program a line or two at a time.


file = open("emails")
for line in file:

These lines are very much like the first two lines of the previous program; the
only difference is the name of the file in the first line. In fact, this pattern of
code is common in programs that read a file and do something with every line
of it.
name, email = line.split(",")

The part line.split(",") splits line into two pieces at the comma. The result
is two things: the piece before the comma and the piece after the comma. We
give the names “name” and “email” to those two things.
if name == "John Davis":

This says: if name equals (in other words, is the same as) “John Davis”, do
what comes next. Python uses “==”, two adjacent equals-signs, for this kind
of comparison. You might think that just a single equals-sign would mean
“equals”, but Python uses “=” to associate a name with a thing, as we have
seen. So, to avoid any possible ambiguity, Python uses a different symbol for
comparing two things for equality.
print(email)

This displays the result that we want.

As our final example, let's take a very simple computational task: finding the
average of a collection of numbers. They might be a scientist's measurements

7
A first look at Python

of flows in a stream, or the balances in a person's checking account on different


days, or the weights of different boxes of corn flakes. It doesn't matter what
they mean: for purposes of our computation, they are just numbers.

Let's say, for the sake of the example, that they are temperatures. You have
a thermometer outside your window, and you read it at the same time each
day for a month. You record each temperature to the nearest degree, so all
your observations are whole numbers (the mathematical term for these is
“integers”). You put the numbers into a file on your computer, perhaps using
a text-editing or word-processing program; let's say that the name of the file
is “observations”. At the end of the month, you want to calculate the average
temperature for the month.

Example 1.3 shows a Python program that will do that computation. It's a
little longer than the previous two programs, but it's still short and simple
enough that we might call it a “script”.

Example 1.3. Average of a collection of observations


sum = 0
count = 0

file = open("observations")
for line in file:
n = int(line)
sum += n
count += 1

print(sum/count)

Let's look at this program a line or two at a time.


sum = 0
count = 0

To compute the average of the numbers in the file, we need to find the sum
of all the numbers and also count how many there are. Here we give the names

8
A first look at Python

sum and count to those two values. We start both the sum and the count at
zero.
file = open("observations")
for line in file:

As in the previous two programs, these lines say: open the file that we want
and then, for each line of the file, do what comes next. Specifically, do the
lines that are indented, the next three lines.
n = int(line)

A line of a file is simply a sequence of characters. In this case, it will be a


sequence of digits. The program needs to convert that into a single thing, a
number. That's what int does: it converts the sequence of digits into an integer.
We give the name n to the result.
sum += n
count += 1

In Python, “+=” means “add the thing on the right to the thing on the left”.
So, “sum += n” means “add n to sum” and “count += 1” means “add 1 to
count”. This is the obvious way to accumulate the running sum and the running
count of the numbers that the program has seen so far.
print(sum/count)

This step is done after all the numbers in the file have been summed and
counted. It displays the result of the computation: the average of the numbers,
which is sum divided by count.

Notice, by the way, that we've used blank lines to divide the lines of the
program into logical groups. You can do this in Python, and programmers
often do. This doesn't affect what the program does, but it might make the
program a little easier for a person to read and understand.

So now you've seen three very short and simple Python programs. They aren't
entirely typical of Python programs, though, because they illustrate only a
few of the most basic parts of the Python language. Python has many more

9
A little mathematical terminology

features, and you'll learn about many of them in the remaining chapters of
this book. But these programs are enough examples of Python for now.

1.3. A little mathematical terminology


Now we'll introduce a few mathematical terms that we'll use throughout the
book. We won't actually be doing much mathematics, in the sense of deriving
formulas or proving theorems; but, in keeping with the theme of the book,
we'll constantly use mathematical terminology as a vocabulary for talking
about programs and the computational problems that we solve with them.

The first term is set. A set is just an unordered collection of different things.

For example, we can speak of the set of all the people in a room, or the set of
all the books that you have read this year, or the set of different items that
are for sale in a particular shop.

The next term is sequence. A sequence is simply an ordered collection of things.

For example, we can speak of the sequence of digits in your telephone number
or the sequence of letters in your surname. Unlike a set, a sequence doesn't
have the property that all the things in it are necessarily different. For example,
many telephone numbers contain some digit more than once.

You may have heard the word “set” used in a mathematical context, or you
may know the word just from its ordinary English usage. It may seem strange
to call the word “sequence” a mathematical term, but it turns out that

10
A little mathematical terminology

sequences have some mathematical properties that we'll want to be aware of.
For now, just notice the differences between the concepts “set” and “sequence”.

Let's try applying these mathematical concepts to the sample Python programs
that we've just seen. In each of them, what kind of mathematical object is the
data that the program operates on?

First, notice that each program operates on a file. A file, at least as a Python
program sees it, is a sequence of lines. Code like this is very common in Python
programs that read files a line at a time:
file = open("observations")
for line in file:

In general, the Python construct

for element in sequence :

is the Python way to do something with every element of a sequence, one


element at a time.

Furthermore, each line of a file is a sequence of characters, as we have already


observed. So we can describe a file as a sequence of sequences.

But let's look deeper.

Let's take the file of names in our first example (Example 1.1). In terms of the
information that we want to get from it, the file is a collection of names. What
kind of collection? We don't care about the order of names in it; we just want
to see all the names that start with “John”. So, assuming that our lecturer
hasn't included any name twice by mistake, the collection is a set as far as
we're concerned.

In fact, both the input and the output of this program are sets. The input is
the set of names of people who attended the lecture. The output is the set of
members of that input set that start with the letters “John”. In mathematical
terminology, the output set is a subset of the input set.

11
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XXV.

Holborn Viaduct — Omnibuses — Cabs — Hansom's patent — Posting — Mail


coaches — Stage coaches — Hotels.

On all hands, it is admitted that the streets of


London were generally well paved, and there were
but two bad hills, Holborn and Snow Hills, which
were caused by the Valley of the Fleet. This has been
bridged over in our time, but a similar viaduct was
proposed in 1833. This was intended to take down
the houses from the corner of Bartlett's Buildings,
Holborn, to Seacoal Lane, Skinner Street, or, on the
opposite side, from Hatton Garden to the top of
Snow Hill, and erect a level terrace on brick arches
between these points, the houses to be taken down
and set back about fifty feet, or in a line with St.
Andrew's Church, and the arches under the terrace
to be fitted up as shops on Holborn Hill, with a
handsome balustrade on the top. An ornamental arch
was to be turned over Farringdon Street, on the
principle of Highgate Archway. This is, virtually, what
was begun about thirty years later, in 1867.
As the population of London in 1831 (taking the
area as now) was only about a million and a half, it
stands to reason that there would be but about a
quarter of the traffic. The first omnibus started from
the Yorkshire Stingo, Paddington, to the Bank, on
July 4, 1829, and, becoming popular, these vehicles
were very soon multiplied, and, in 1831, there seem
to have been ninety running; for, at a meeting of
omnibus proprietors on September 10th of that year,
it was proposed, in consequence of the danger which
arose from competitive racing, to stop thirty-three of
them, and, as the chairman observed, "this
diminution would leave fifty-seven of them to run, so
that the public would have a regular conveyance
every three minutes from Paddington to the Bank,
from eight in the morning till ten at night."

As a specimen of omnibus amenities about this


time I may mention a police case at Marylebone, on
August 14, 1830. It was for an assault, but that was
of very little moment; it related more to the
convenience and safety of the public, especially the
female portion; for it came out that by some of the
cads (as the conductors were then called) it was
considered fair play to take a lady forcibly from the
steps of an omnibus she was inclined to enter and
push her into another, and that the previous week,
two ladies had been so mauled by four strong
fellows, that they would not ride at all.

The royal assent was given on September 22,


1831, to "An Act to amend the laws relating to
Hackney Carriages," etc., by which it was enacted
that, up to January 5, 1833, they should be limited to
twelve hundred, and, after that date, there was to be
no limitation to their number, except that caused by
the law of demand and supply. The hackney coach
was a cumbrous vehicle with two horses, and, in
1823, one-horsed vehicles were introduced, called
cabriolets, speedily shortened into cabs. They began
modestly with twelve, and in 1831 had increased to
one hundred and sixty-five. They were somewhat
peculiar, as the driver sat by the side of his fare,
although not with him, and the possibility of the
coachman seeing the amount he was to be given,
and the chance of his upsetting his passenger in case
it did not meet his expectations, is humorously
described in Pickwick.
On December 23, 1834, Joseph Aloysius Hansom,
an architect, took out a patent, No. 6733, for "a
vehicle for conveying loads, etc.," and from that time
to this his name has been inseparably connected in
England with cabs. Not that his cab was like the
present "hansom," which is a product of much
evolution. There was no back seat for the driver, and
its "safety" consisted in its cranked axle. He sold his
rights to a company for £10,000, but never got a
penny piece of it. The only money he ever got out of
it was £300, which, when the company had got into
a muddle, was paid him to take temporary
management and put things straight again.
Thanks to Mr. John Macadam, whose system of
using broken stones is still adopted, the country
roads were very much improved. He, unlike Hansom,
received £10,000 from Parliament, and was
appointed Surveyor-General of the Metropolitan
roads in 1827. He died in 1836.

In describing travelling in England during this


reign, I cannot do better than quote from Baron
d'Haussez, because a foreigner looks upon things
with a far more critical eye than a native, who is
always used to them. Says he—
"The taste for travelling, an expensive taste in any country,
is truly a ruinous one in England. If the means of satisfying it
are numerous, and accompanied by all that can promote
pleasure, one is steeled against this seductive consolation by
the perpetual warning of a speedily drained purse.

"Posting, placed on a totally different footing from that


service in the rest of Europe, is not the object of an exclusive
privilege. By means of a licence, which cannot be refused,
relays of post-horses are established according to the caprice
or will of those who possess them. The rivalry arising from
this practice does not lower the price of posting, which,
London excepted, is nearly the same on all roads, and differs
but little from the price of relays in France. The number of
horses is always fixed at two or four, without regard to the
number of travellers, or to the form or weight of the
carriages. When you desire a post-chaise, the innkeeper is
obliged to furnish it, without your paying an additional price.
These chaises, in the shape of our coupés, are well hung, and
very clean and commodious.

"England has not, as we find in France, a breed of horses


specially appropriated to posting. The greater part of the
post-horses in England are hunters or carriage-horses, which,
having become unfit for either of these purposes, wear out
the remnant of their strength in post-chaises, before they are
transferred to hackney coaches and waggons. Their speed
answers in a great degree to what one would expect from
their breed. You travel at the rate of eight or nine miles an
hour (about three and a half leagues), which includes the
time of changing horses.

"The height of the postillions (always chosen among the


smallest men), and their dress, consisting of a jacket, short
breeches, and half boots, are calculated with a view to reduce
to the smallest possible compass the burden of the horses.
There is no difference between the town harness and that
which is kept for posting. They are both in excellent
condition.

"The mail coaches destined for the transport of letters are


carriages with four inside and six outside places. Behind the
coach the guard is seated, with a blunderbuss and a pair of
pistols before him. These coaches travel at the rate of ten
miles, or four leagues an hour; but their small size (for the
English, in general tall and thick, appear to have little regard
to their personal proportions in the size of their carriages),
and the short time they stop to refresh, render them very
unpleasant modes of conveyance.

"Stage coaches are very elegant carriages, built to carry


fifteen or eighteen travellers, and a considerable weight in
packets, but on admirable roads. This is an indispensable
condition. Without it, the height of the carriages, the
arrangement of the whole of the luggage on the imperial, and
the lightness of the body and the axletree, would give rise to
frequent accidents.

"The inside of the coach contains only four places. The seat
of the coachman, and another seat placed immediately
behind it, admit of six persons, and two seats facing each
other, at the hind wheels, afford places for six or eight more.
These seats are fixed over boots or boxes for stowing away
the luggage. Such parcels as these cannot contain are placed
on the imperial.

"The desire to breathe the fresh air, rather than economical


considerations, induce even the richest English to give a
preference to outside places. They only go inside when
compelled by bad weather. The place most in request—one
knows not wherefore—is to the left of the coachman; it is
considered as the place of honour, and is reserved for
fashionables, and even for lords, who do not disdain to travel
thus. The sole advantages, which such a station appeared to
me to present, were the being placed near a well-dressed
coachman, and the escaping the chance of travelling by the
side of a butcher, a shoemaker, or some other individual of
that class. Each time the coachman descends from his box,
his neighbour has the advantage of being made the forced
depositary of his reins and whip. These are placed in your
hands, as they are taken out of them again, without the least
ceremony.

"The appointments of an English coach are no less elegant


than its form. A portly looking coachman seated on a very
high coach-box, well dressed, wearing white gloves, a
nosegay in his button-hole, and his chin enveloped in an
enormous cravat, drives four horses perfectly matched and
harnessed, and as carefully groomed as when they excited
admiration in the carriages of Grosvenor and Berkeley
Squares. Such is the manner in which English horses are
managed, such, also, is their docility, the effect either of
temperament or training, that you do not remark the least
restiveness in them. Four-horse coaches are to be seen
rapidly traversing the most populous streets of London,
without occasioning the least accident, without being at all
inconvenienced in the midst of the numerous carriages, which
hardly leave the necessary space to pass. The swearing of
ostlers is never heard at the relays, any more than the
neighing of horses; nor are you interrupted on the road by
the voice of the coachman, or the sound of his whip, which
differs only from a cabriolet whip in the length of the thong,
and serves as a sort of appendage, rather than a means of
correction in the hand which carries it. In England, where
everything is so well arranged, where each person knows so
well how to confine himself to the exigencies of his proper
position, the horses do better what they have to do than the
horses of other countries, and that, too, without the need of a
brutal correction. One may travel from one end of England to
the other without hearing the sound of a whip, or the
hallooing of conductors, which in France fall so disagreeably
on the ears of travellers.

"Among the wonders of English civilization, the inns should


be mentioned. In many of the larger towns they are
magnificent, and they are good and well supplied in the
smallest. In the greater part of them the servants are in
livery, and in all their attendance is prompt and respectful. On
their arrival, travellers are received by the master of the
house, whose decent dress indicates a respectful feeling
towards strangers. Introduced into a well-heated, well-
furnished room, they have never to wait for a meal, the
simplicity of which, in the way of cookery, is atoned for by the
elegance, often the richness, of the plate and ware, and the
superior quality of the meat. A sleeping-room, as comfortable
as this kind of apartment (so neglected in England) can be,
completes the agrément of your sojourn. Your discontent
does not commence till the exorbitant bill proves that such
attentions, far from being disinterested, are, on the contrary,
dearly charged for. Seldom do you separate from your host
with a reciprocation of politeness. Yet, notwithstanding the
coldness with which his attentions are received, the landlord
does not cease to remain by the side of the traveller till his
carriage is in motion."
With regard to the London hotels, travellers by the
coaches generally stopped where they stopped, and
were very fairly treated. Of course, there was none
of the palatial magnificence of the modern hotel, but
there was an amount of homely comfort to which the
people of those days were accustomed. The West
End hotels, save those for awful swells, were about
Covent Garden, and Morley's Hotel at Charing Cross
was one of the best. The first monster hotel in
London was the Great Western, and its financial
success led the way to the palaces that now adorn
our West End thoroughfare.

There is an amusing anecdote re "Mine Host"


given in the New Sporting Magazine, and quoted in
the Times of March 27, 1835—
"Innkeeper's Ways.

"I will conclude with a story told me the other day, by a


Kentish gentleman, of an innkeeper's 'ways' on the Dover
Road. Two gentlemen having dined and stayed all night,
called for the bill in the morning, and one of them happened
to be within earshot when the waiter went to the landlord to
have it made out, and overheard the following colloquy:
Waiter: 'Please, sir, the gemmen in No. 5 wants their bill.'—
Landlord: 'Very well' (taking down a printed form), 'let me
hear what they had.'—Waiter: 'Soup, sir.'—Landlord: 'Soup;
very well; what sort was it?'—Waiter: 'Mock turtle.'—Landlord:
'Mock turtle, 3s. Did they make any remark about it?'—
Waiter: 'No, sir; only one of them said it was werry good.'—
Landlord: 'Did they eat of it twice?'—Waiter: 'Yes, sir.'—
Landlord: 'Oh, then, mock turtle, 5s.; now go on.'—Waiter:
'Fried sole and shrimp sauce.'—Landlord: 'Fried sole, 2s.;
shrimp sauce, 1s.; 3s. Did they make any remark about
that?'—Waiter: 'One of them said that the fish was werry
fresh.—Landlord: 'Indeed! then, fried sole, 3s.; shrimp sauce,
1s. 6d.; 4s. 6d. Now go on.'—Waiter: 'Small leg of Welsh
mutton, potatoes, and French beans.'—Landlord: 'Mutton,
5s.; potatoes, 1s.; French beans, 5s.; rather early for French
beans, isn't it?'—Waiter: 'Yes, sir; both the gemmen remarked
that it was werry early.'—Landlord: 'Oh, then, French beans,
10s.'"

Of the coaching hotels enough has been written


from Smollett's time, or before, to date; and, as for
their number, any visitor to Barnet can judge, by
those that remain, several having been made to
serve other purposes. This was the first change out
of London, on the great North Road, and even I
remember fifteen coaches running each way, and the
last one being run off. I think it was either the Luton
Coach or the Bedford Times.
CHAPTER XXVI.

Steam carriages on roads — Commission thereon — Steam omnibus — Railways —


A nuisance — Railways started during the reign — Opening of the Greenwich
Railway.

But the road was not monopolized by horseflesh.


Steam was asserting itself, and many were the trials
of steam carriages on the turnpike roads. In 1821 Mr.
Julius Griffith invented, and Messrs. Bramah
manufactured, a carriage, on which the engineer sat
in front, and two directors or steersmen behind, in
vehicles separated from the carriage, which swung
easily on a variety of springs fastened into a strong
connecting frame. The error of this invention lay in
the boiler, which consisted of 114 tubes. These,
unfortunately, would not always contain the water;
and, when empty, they became so heated, that no
force-pump could inject the water. In 1822, 1824,
and 1825, Mr. David Gordon tried his hand on steam
carriages and failed. In 1829 Sir James Anderson and
Mr. James constructed one, under the patents
obtained by the latter gentleman in 1824 and 1825,
and are said to have worked the engine at a pressure
of two hundred pounds each square inch of the
piston. In 1827 Mr. Goldsworthy Gurney patented
one, as did also Messrs. Hill and Burstall in 1828.

There was one running in August, 1830, belonging


to Messrs. Summers and Co., which began its
journey by bursting a pipe. This repaired, it utterly
demoralized itself by running into a turnpike gatepost
at Turnham Green, and had to be taken home.
Anyhow they must have become fairly common, for
we read in the Times, May 12, 1831—
"Steam Carriages on Common Roads.

"Some of the advantages to the public from the use of


steam on the turnpike roads already begin to show
themselves. Previous to the starting of the steam coach
between Gloucester and Cheltenham, the fares were four
shillings each person—now the public are taken by all the
coaches at one shilling per head. On Tuesday morning the
steam coach took thirty-three passengers from Cheltenham to
Gloucester in fifty minutes."

Again, Times, June 7, 1831, quoting the Glasgow


Chronicle, says—
"Mr. Gurney's[22] steam carriage was, on Wednesday night,
blown to pieces by an explosion of the boiler. The catastrophe
occurred in the square of the cavalry barracks, where the
carriage was exhibiting. It had gone round the square several
times, and stopped at one corner of it, where some people
got out. Two boys, sons of Mr. Maclure, of the Port Eglinton
Inn, at that time entered, and were about to be followed by
two gentlemen, when the boiler burst with a tremendous
explosion, and shattered the vehicle into numberless pieces.
The two boys were very seriously injured in the face and
other parts of the body, and they now lie in very precarious
circumstances."

The road steam carriage was such a novelty, that


people hardly knew what to make of it, so a Select
Committee of the House of Commons upon it was
appointed, who reported thereon to the House on
October 12, 1831. The conclusion of the report was
as follows:—
"Sufficient evidence has been adduced to convince your
Committee—

"1. That carriages can be propelled by steam on common


roads at an average rate of ten miles per hour.

"2. That at this rate they have conveyed upwards of


fourteen passengers.

"3. That their weight, including engine, fuel, water, and


attendants, may be under three tons.

"4. That they can ascend and descend hills of considerable


inclination with facility and safety.

"5. That they are perfectly safe for passengers.

"6. That they are not (or need not be, if properly
constructed) nuisances to the public.
"7. That they will become a speedier and cheaper mode of
conveyance than carriages drawn by horses.

"8. That, as they admit of greater breadth of tire than other


carriages, and as the roads are not acted on so injuriously as
by the feet of horses in common draught, such carriages will
cause less wear of roads than coaches drawn by horses.

"9. That rates of toll have been imposed on steam carriages


which would prohibit their being used on several lines of road,
were such charges permitted to remain unaltered."

On August 20, 1832, we hear of a steam carriage,


constructed by a Mr. Hancock, intending to make an
experimental trip to Windsor, and coming to grief at
Dachet. In November and December of the same
year we learn that a steam carriage, constructed by
Captain Macirone and Mr. Squire, was running about
Paddington, and that "the jolting was not much
greater than an ordinary stage coach." In the Times
of April 25, 1833, we read of a
"Steam Omnibus.

"Monday afternoon an omnibus, worked by steam on a new


and ingenious principle, was tried on the Paddington Road.
The machine altogether does not exceed the space which an
ordinary omnibus, with horses attached, would occupy, and
the appearance is particularly neat. The body is capable of
containing fourteen persons, the engine dividing that from the
furnace in the rear. The passengers experience no
inconvenience from heat, and, coke being the fuel employed,
there is no annoyance from smoke. The engine works on a
crank, not on an axle, and the propelling power is applied to
the wheels by means of iron chains. The chief
recommendation, that which timid persons will consider most,
is that there can be no possibility of explosion. The propelling
power is equal to fifteen or twenty miles an hour; but, even
when the steam is raised to its very highest pressure, there is
no risk, the water being deposited in several iron pipes, or
what are termed chamber boilers, with a valve to carry off the
superfluous steam. The guide, who sits in front, has complete
control of the vehicle, and can arrest its progress
instantaneously. It is intended to ply regularly from
Paddington to the Bank."

Captain Macirone's steam carriage was repeatedly


noticed by the Press, and in 1834 there is an
advertisement of a company to work Dr. Church's
steam carriage; but all the schemes came to nought.

When William IV. came to the throne there were


practically no railways for passenger traffic; and it
was during his reign that nearly all the main lines in
England were projected. I now marvel at their having
attained so rapid a popularity, for the travelling was
very uncomfortable. The idea of a stage coach was
very difficult to get rid of, and the carriages were
subdivided so as to represent it as much as possible
—even their outsides were modelled, as far as could
be, to look like a coach, and to this day a train is, in
railway parlance, made up of so many coaches. The
first class were padded and cushioned, but were very
stuffy, having small windows; the second class were
of plain painted wood, narrow seats, no room for
one's legs, and very small windows; in the third class
there were no seats, it was simply a cattle truck in
which every one stood up, and as there was no roof,
it was rather lively travelling in wet weather.

Railways were soon considered as a nuisance to


the public, and on March 30th, at York, an action of
Rex v. Pease and others was tried. It was an
indictment for a nuisance against the Stockton and
Darlington Railway Company, which was opened on
September 27, 1825. By an Act of Parliament, passed
in 1821, the defendants were authorized to form a
railway from Darlington to Sunderland, and, by
another Act passed in 1823, they were authorized to
use locomotive engines thereon. The railway which,
it was agreed, had been formed upon the line
pointed out in the Act of Parliament, was opened for
public use in 1825. Only one steam engine was at
first used; but the number gradually increased till
there were seven in operation. This increase had
been rendered necessary by the increasing business
on the railway.

For about a mile and three-quarters the railway


runs in a parallel line with the high-road leading from
Yarm to Stockton, the two roads being at an average
distance from each other of fifty yards. The nuisance
complained of was the fright and danger which the
noise and the smoke of the steam engines
occasioned to passengers on this part of the
highway. A variety of witnesses proved that accidents
frequently happened in consequence of horses taking
fright at the steam engine. Counsel for the railway
stated that he was willing to admit that his clients
had been guilty of a nuisance, unless their conduct
was justified by the Act of Parliament, according to
the directions of which, the railway had been formed,
and the steam engines used. He suggested,
therefore, that the best mode would be for the jury
to return a special verdict, finding the facts already
proved, and also that the defendants had used the
best engines they could procure, and availed
themselves of every improvement offered. The
counsel for the prosecution, after some deliberation,
agreed to the proposal, and a nominal verdict of
guilty was recorded.

The first railway opened in this reign was in 1830,


the Liverpool and Manchester, which melancholy
event has already been noticed. In December, 1831,
was opened that between Dundee and Newtyle. In
1833 the following railways were projected. The
London and Bristol (G.W.R.), London and
Southampton (L. & S.W.R.), London and Birmingham
(L. &. N.W.R), London and Brighton, and London and
Greenwich; in 1834 the Great Northern Railway; in
1835 the Eastern Counties Railway (G.E.R.), and the
Commercial or Blackwall Railway. The other railways
opened for traffic were the Leeds and Selby,
September 22, 1834; Dublin and Kingdown on
December 17, 1834; London and Greenwich,
December 14, 1836, and Liverpool and Birmingham,
July 4, 1837. Besides these there were many others
projected, some of which came to nought. Take, for
instance, one column of advertisements (p. 2, c. 5,
Times, April 18, 1836)—South Western Railway,
Padstow Breakwater, and Rock Delabole, Camelford,
Callington, and Plymouth Railway, South London
Union Railway, Bristol and Gloucestershire Railway,
Margate and Ramsgate Railway, Ramsgate,
Canterbury, Sandwich, Deal and Dover Railway,
Gloucester and Hereford Railway, Harwich Railway,
Westminster and Deptford Railway, and the Great
Central Irish Railway.

In fact, the satire in John Bull of April 9, 1836, was


not altogether undeserved—
"There is always a clown in a pantomime who knocks his
head against a door, and tumbles on his nether end, and
grins and distorts his limbs, and does, in short, a thousand
feats to make the ridiculous performance more ridiculous still.
In the pantomime of railroads, in which the tricks are
innumerable, there is a clown, one so supereminently
ridiculous, that if Grimaldi were still young and active enough
to wear his blue tuft and wafer-dotted unmentionables, he
would be jealous. The scheme to which we allude is one
called by the sounding name of an International Railway—
London, Paris, and Brussels, by Dover and Calais; and there
are blanks left in the prospectus (and likely to be left) for the
names of French patrons and Belgian patrons, and provincial
directors, and all the rest of it; and the beginning of the
suggestion is, that people are to go to Croydon in the first
instance, as the shortest way to Belgium. Croydon seems an
odd starting-point for Brussels; however, the prospectus infers
that London has something to do with it; how much, we may
venture to guess, by finding that the railroad communication
with London is disavowed before the committee to whom the
Bill is referred. As to Brussels and Paris, they will come, of
course, when once the sea is crossed; but we must say that
the Grimaldi railway, which renders it necessary to proceed by
the old mode of travelling to Croydon in order to be steamed
to Brussels, is very like paying a shilling to be rattled in an
omnibus from London to a field in Bermondsey marsh, in
order to climb up a flight of stairs to be rattled along the
railroad at Deptford, at which place the traveller is suddenly
ejected, his object being Greenwich (after which town the
absurdity is delusively named), which it neither does, nor,
thanks to the wisdom of Parliament, ever will reach; so that,
what with the coloured hearse through the City, before you
get to the starting-place in the bog, the climb upstairs, and
the wearisome walk through the mud of the Lower Road to
Greenwich, after you come down again, you would save
exactly six pennies and three-quarters of an hour if you
stepped into a fast-going coach at the Shoulder of Mutton or
the Salopian at Charing Cross, and went slap bang to
Greenwich itself, for the trifling charge of one shilling. This is
absurd for a short affair and a matter of joke; but the railroad
from Croydon to Brussels, for a serious concern and a long
business, 'beats Bannagher,' as Mr. O'Connell says."

The Greenwich Railway referred to was opened by


the Lord Mayor and civic authorities, on December
14, 1836, but only as far as Deptford; and the whole
affair seems to have been a muddle. The Times of
December 15 says—
"On the arrival of the several trains at Deptford the
occupants of the carriages were allowed to get out; but here
the arrangements fell far short of what we expected, for no
preparation was made for their return. Many who had got out
in the hopes of being present at the presentation to the Lord
Mayor, and others who wished to regale themselves at some
of the neighbouring inns at Deptford, could not, from the
density of the crowds below the railway, get out; and, on
retracing their steps to the railway, they found it a work of
still greater difficulty and danger to return to the carriages
from which they had alighted. Many who had taken the
precaution to notice the name of the engine which drew the
train, and the number of the carriage which brought them
down, got back in the line between two trains, but were told
by the conductors that they could not return by that way
without great risk, for that the trains would return
immediately. In consequence of this, many persons who came
down by the trains went on to Deptford, and thence to town
by the coaches."
CHAPTER XXVII.

Cases of wife selling — Duelling — Cases of — O'Connell and D'Israeli — Other


duels.

There were two amusements somewhat


fashionable in this reign, wife selling and duelling.
The former is still in existence, the latter is extinct in
England. The halter round the neck was used when
the wife was sold at market, it being considered that,
being thus accoutred, she was on a level with the
cattle, and thus could be legally sold. Here is a ballad
of the period thereon.
"Sale of a Wife.

"Attend to my ditty, you frolicsome folk,


I'll tell you a story—a comical joke;
'Tis a positive fact, what I'm going to unfold,
Concerning a woman who by auction was sold.

Chorus.

Then long may he flourish, and prosper through life,


The sailor that purchased the carpenter's wife.

"A carpenter lived not a mile off from here,


Being a little, or rather, too fond of his beer;
Being hard up for brass—it is true, on my life,
For ten shillings, by auction, he sold off his wife.

"The husband and wife they could never agree,


For he was too fond of going out on the spree;
They settled the matter, without more delay,
So, tied in a halter, he took her away.

"He sent round the bell-man, announcing the sale,


All in the hay-market, and that without fail;
The auctioneer came, with his hammer so smart,
And the carpenter's wife stood up in a cart.
"Now she was put up without grumble or frown,
The first bid was a tailor, that bid half a crown;
Says he, 'I will make her a lady so spruce,
And fatten her well upon cabbage and goose.'[23]

"'Five and sixpence three farthings,' a butcher then said,


'Six and ten,' said a barber, with his curly head;
Then up jump'd a cobbler, said he, 'In three cracks,
I'll give you nine shillings and two balls of wax.'

"'Just look at her beauty,' the auctioneer cries;


'She's mighty good-tempered, and sober likewise.'
'Damme,' said a sailor, 'she's three out of four,
Ten shillings I bid for her, not a screw more.'

"'Thank you, sir, thank you,' said the bold auctioneer,


'Going for ten. Is there nobody here
Will bid any more? Is not this a bad job?
Going! Going! I say—she's gone for ten bob.'

"The hammer was struck; that concluded the sale,


The sailor he paid down the brass on the nail;
He shook hands with Betsy, and gave her a smack,
And she jumped straddle-legs on to his back.

"The people all relished the joke, it appears,


And gave the young sailor three hearty good cheers;
He never cried stop, with his darling so sweet,
Until he was landed in Denison Street.

"They sent for fiddler and piper to play,


They danced and they sung, till the break of day;
Then Jack to his hammock with Betsy did go,
While the fiddler and piper played 'Rosin, the beau.'"
I have eleven cases of wife selling in this reign,
copied from the Times, and I have no doubt I have
overlooked some more. The first is—
"Selling a Wife.

"The following memorandum (says the Stockport


Advertiser), drawn upon a 1s. 6d. stamp, will best explain the
nature of a bargain between two fellows at a beer shop, in
the Hillgate, in this town. Milward is a butcher, and was last
week fined before our magistrates for using uneven balances
in his trading transactions. The other persons are unknown to
us:—

"'I, Booth Milward, bought of William Clayton, his wife, for


five shillings, to be delivered on the 25th of March, 1831, to
be delivered in a alter at Mr. John Lomases house.

"'William Clayton.
"'Witnesses: Joseph Gordon, G. Wood, George Whalley.'"

The next is from the Times, February 25, 1832—


"Buying and Selling Wives.

"In an evening paper we find the following story: 'A most


disgusting and disgraceful scene happened in Smithfield
Market on Monday last, which at the present day is of very
rare occurrence. About two o'clock in the afternoon a fellow
came into the market leading his wife by a halter, and gave
her to a drover, desiring him to tie her to the pens and sell
her to the best bidder. The woman, who did not appear to be
above twenty-five years of age, and not bad looking, suffered
herself to be tied up very quietly. A crowd of persons soon
gathered round, and a man of rather respectable appearance
entered into a negotiation with the drover for the purchase of
the wife; and, after some higgling, she was finally knocked
down to him for the sum of ten shillings. The money was
paid, but the drover refused to release her except on
payment of two shillings as his commission for the sale which
he had effected. Some confusion took place about the
demand, but it was eventually paid, and she was released
from the pens, opposite the Half Moon public house, and
delivered to her purchaser, who appeared highly pleased with
his bargain. The parties adjourned to a neighbouring public
house, where the late husband spent the greater part of the
money in brandy and water.'"

The following is from the Times of April 26, 1832


(from the Lancaster Herald), and is somewhat out of
the common run of these affairs:—
"Sale of a Wife by her Husband at Carlyle.

"On Saturday, the 7th instant, the inhabitants of this city


witnessed the sale of a wife by her husband, Joseph
Thompson, who resides in a small village about three miles
from this city. He rents a farm of about forty-two or forty-four
acres, and was married at Hexham in the year 1829 to his
present wife. She is a spruce, lively, and buxom damsel,
apparently not exceeding twenty-two years of age, and
appeared to feel a pleasure at the exchange she was about to
make. They had no children during their union, and that,
together with some family disputes, caused them by mutual
agreement to come to the resolution of finally parting.
Accordingly the bellman was sent round to give public notice
of the sale, which was to take place at twelve o'clock. This
announcement attracted the notice of thousands. She
appeared above the crowd, standing on a large oak chair,
surrounded by many of her friends, with a rope or halter
made of straw about her neck. She was dressed in rather a
fashionable country style, and appeared to some advantage.
The husband, who was also standing in an elevated position
near her, proceeded to put her up for sale, and spoke nearly
as follows:—

"'Gentlemen, I have to offer to your notice my wife, Mary


Ann Thompson, otherwise Williamson, whom I mean to sell to
the highest and fairest bidder. Gentlemen, it is her wish, as
well as mine to part for ever. She has been to me only a
bosom serpent. I took her for my comfort and the good of my
house, but she became my tormentor, a domestic curse, a
night invasion, and a daily devil. (Great laughter.) Gentlemen,
I speak truth from my heart when I say, "May God deliver us
from troublesome wives and frolicsome widows!" Avoid them
as you would a mad dog, a roaring lion, a loaded pistol,
cholera morbus, Mount Etna, or any other pestilential
phenomena in nature.

"Now I have shown you the dark side of my wife, and told
you her faults and her failings, I will introduce the bright and
sunny side of her, and explain her qualifications and her
goodness. She can read novels and milk cows; she can laugh
and weep with the same ease that you can take a glass of ale
when thirsty; indeed, gentlemen, she reminds me of what the
poet says of women in general—

"'Heaven gave to women the peculiar grace,


To laugh, to weep, to cheat the human race.'

"She can make butter and scold the maid; she can sing
Moore's Melodies, and plait her frills and caps; she cannot
make rum, gin, or whisky, but she is a good judge of the
quality from long experience in tasting them. I therefore offer
her, with all her perfections and imperfections, for the sum of
50s.
"After an hour or two, she was purchased by Henry Mears,
a pensioner, for the sum of 20s. and a Newfoundland dog.
The happy people immediately left town together, amidst the
shouts and huzzas of the multitude, in which they were joined
by Thompson, who, with the greatest good humour
imaginable, proceeded to put the halter which his wife had
taken off round the neck of his Newfoundland dog, and then
proceeded to the first public-house, where he spent the
remainder of the day."

In the Times of March 25, 1833, is the following:—


"A grinder, named Calton, sold his wife publicly in the
market place, Stockport, last Monday week. She was
purchased by a shopmate of her husband for a gallon of beer!
The fair one, who had a halter round her neck, seemed quite
agreeable.—Blackburn Gazette."

The Times of May 24th, 1834, quoting the Paisley


Advertiser, says—
"Sale of a Wife.

"Monday night a party of doughty neighbours met in a


house in New Sneddon to enjoy a tankard or two of reaming
swats, and to decide by which of the rival 'best possible
instructors' they were, henceforth, to be enlightened. In the
course of the discussion, one of them announced his intention
of setting up a dram shop, and stated that there was only one
article wanting. 'What was that?' 'A wife!' 'A wife!' exclaimed
the host—whose name is as the name of the upper part of
the garment in which the humble daughters of St. Mirren
delight to conceal their beauties—'I will sell you mine for
twenty pounds Scots.' Some higgling took place, in the course
of which the virtues of the wife shone out with such
conspicuous lustre that her price was raised to twenty pounds
sterling. This sum the purchaser agreed to pay, a contract
was drawn out, and signed by three witnesses, the conditions
of sale being that the money was to be tabled, and the
transfer completed by next day, at noon.

"Next day came, and found the seller, the purchaser, and
their witnesses once more assembled, discussing at once the
terms of agreement and a can of grog. Some of the witnesses
seemed to think that the joke was carried far enough, and
proposed that the whole proceedings should be nullified on
the host forfeiting £1, to be 'melted,' in the house; but the
host was too well up to trap to be wheedled out of his £20,
and saddled with his wife to boot; he therefore persisted in
the fulfilment of the contract, and, as the purchaser was
equally averse to a rue bargain, arrangements were put in
operation to complete the transaction.

"Meanwhile, the wife, whose good qualities may be judged


of by the great rise which took place in her price, while the
terms were under discussion, got a hint of the negotiations
that were pending, and, being a good deal nettled that her
opinion should not have been asked in an affair in which she
was so nearly concerned, sallied out to a neighbouring court,
known by the name of 'Little Ireland,' and sounded the tocsin
of alarm. A much smaller matter than the sale of a wife was
enough to agitate 'Little Ireland.' With ire akin to that which
animated the bosom of 'Cutty Sark' and her compeers, as
they sallied out of Alloway Kirk to avenge themselves on Tam
o'Shanter and his mare Meg, sallied out the daughters of
Little Ireland to avenge the insult thus offered to one of the
best half of creation. Every damsel who could wag a tongue—
mercy on us, how numerous a class!—every one who could
wield a poker, fender, or pair of tongs, flew to arms, and
resolved on a simultaneous attack; while the high contracting
parties, and their assistant negotiators were within, discussing
terms, wholly ignorant of the storm that was brewing around
them. How the victory would have gone it is no way difficult
to predict; but before active hostilities commenced, the police
arrived, and conveyed the negotiators to the office, where
they were detained until the vast crowds which had collected
had dispersed, and until security had been given that
appearance would be made next day. There the whole party
were brought before the magistrates, and looked exceedingly
foolish on the occasion. No such an affair as the sale of a wife
seems ever to have been heard of in these northern latitudes,
and, as the fiscal knew from the parricide case of old, that to
prescribe a punishment for a crime was a powerful means to
get the crime introduced, he resolved not to be privy to such
a doing, and, therefore, restricted his charge to a breach of
the peace. The magistrate did not find that a breach of the
peace could be brought home to the parties; and, after
animadverting in severe terms on the disgraceful nature of
such proceedings, and addressing the salesman and
purchaser in terms which, we dare say, they will not soon
forget, he dismissed them from the bar. The purchaser, who is
verging on three score years and ten, seemed to have come
into court predetermined to appeal, and declared that a
bargain was a bargain; but, with the whisky still buzzing in his
head, he appealed at a wrong time, and tabled his shilling
before the sentence of dismissal was pronounced."

The lady got the best of it on another occasion,


according to the Halifax Express, quoted in the Times
of April 4, 1836—
"On Wednesday, May Day Green, Barnsley, was the scene
of an extraordinary encounter. A woman beat her husband on
the face till the blood flew about; he, in turn, sent the
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!

ebookname.com

You might also like