100% found this document useful (1 vote)
115 views

Full download Problem Solving with Algorithms and Data Structures Using Python SECOND EDITION Bradley N. Miller pdf docx

Algorithms

Uploaded by

koshiemhur
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)
115 views

Full download Problem Solving with Algorithms and Data Structures Using Python SECOND EDITION Bradley N. Miller pdf docx

Algorithms

Uploaded by

koshiemhur
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

Problem Solving with Algorithms and Data


Structures Using Python SECOND EDITION Bradley N.
Miller

https://ebookname.com/product/problem-solving-with-
algorithms-and-data-structures-using-python-second-edition-
bradley-n-miller/

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...

ADTs Data Structures and Problem Solving with C 2nd


Edition Nyhoff

https://ebookname.com/product/adts-data-structures-and-problem-
solving-with-c-2nd-edition-nyhoff/

ebookname.com

Data Structures and Algorithms with JavaScript 1st Edition


Michael Mcmillan

https://ebookname.com/product/data-structures-and-algorithms-with-
javascript-1st-edition-michael-mcmillan/

ebookname.com

Essential Algorithms A Practical Approach to Computer


Algorithms Using Python and C Second Edition Rod Stephens

https://ebookname.com/product/essential-algorithms-a-practical-
approach-to-computer-algorithms-using-python-and-c-second-edition-rod-
stephens/
ebookname.com

Magoúla Pavlína A Middle Bronze Age Site in the Soúrpi


Plain Thessaly Greece 1st Edition Corien Wiersma

https://ebookname.com/product/magoula-pavlina-a-middle-bronze-age-
site-in-the-sourpi-plain-thessaly-greece-1st-edition-corien-wiersma/

ebookname.com
Biology Cliffs AP 2nd Edition Phillip E. Pack Ph.D.

https://ebookname.com/product/biology-cliffs-ap-2nd-edition-phillip-e-
pack-ph-d/

ebookname.com

Final FRCR Part A Modules 1 3 Single Best Answer MCQS


MasterPass 1st Edition Robin Proctor (Editor)

https://ebookname.com/product/final-frcr-part-a-modules-1-3-single-
best-answer-mcqs-masterpass-1st-edition-robin-proctor-editor/

ebookname.com

Frommer s Seattle 2010 Karl Samson

https://ebookname.com/product/frommer-s-seattle-2010-karl-samson/

ebookname.com

Applications to Polymers and Plastics 1st Edition Stephen


Z.D. Cheng (Eds.)

https://ebookname.com/product/applications-to-polymers-and-
plastics-1st-edition-stephen-z-d-cheng-eds/

ebookname.com

Studying Religion An Introduction Third Edition Russell T.


Mccutcheon

https://ebookname.com/product/studying-religion-an-introduction-third-
edition-russell-t-mccutcheon/

ebookname.com
JavaScript and DHTML cookbook 2nd ed Edition Danny Goodman

https://ebookname.com/product/javascript-and-dhtml-cookbook-2nd-ed-
edition-danny-goodman/

ebookname.com
Problem Solving with Algorithms and
Data Structures
Release 3.0

Brad Miller, David Ranum

September 22, 2013


CONTENTS

1 Introduction 3
1.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 What Is Computer Science? . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4 Review of Basic Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.5 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.6 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
1.7 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

2 Algorithm Analysis 41
2.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.2 What Is Algorithm Analysis? . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.3 Performance of Python Data Structures . . . . . . . . . . . . . . . . . . . . . 52
2.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.5 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.6 Discussion Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
2.7 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60

3 Basic Data Structures 61


3.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.2 What Are Linear Structures? . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
3.3 Stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
3.4 The Stack Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . 64
3.5 Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.6 Deques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.7 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.8 The Unordered List Abstract Data Type . . . . . . . . . . . . . . . . . . . . . 98
3.9 Implementing an Unordered List: Linked Lists . . . . . . . . . . . . . . . . . 98
3.10 The Ordered List Abstract Data Type . . . . . . . . . . . . . . . . . . . . . . 108
3.11 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.12 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
3.13 Discussion Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
3.14 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113

4 Recursion 117
4.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
4.2 What is Recursion? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

i
4.3 Stack Frames: Implementing Recursion . . . . . . . . . . . . . . . . . . . . . 123
4.4 Visualising Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
4.5 Complex Recursive Problems . . . . . . . . . . . . . . . . . . . . . . . . . . 133
4.6 Exploring a Maze . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
4.7 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
4.8 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
4.9 Discussion Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
4.10 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

5 Sorting and Searching 147


5.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.2 Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
5.3 Sorting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
5.4 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
5.5 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
5.6 Discussion Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
5.7 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183

6 Trees and Tree Algorithms 185


6.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.2 Examples Of Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
6.3 Vocabulary and Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
6.4 Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
6.5 Priority Queues with Binary Heaps . . . . . . . . . . . . . . . . . . . . . . . 198
6.6 Binary Tree Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
6.7 Tree Traversals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
6.8 Binary Search Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
6.9 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
6.10 Key Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
6.11 Discussion Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
6.12 Programming Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

7 JSON 235
7.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
7.2 What is JSON? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
7.3 The JSON Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235

ii
Problem Solving with Algorithms and Data Structures, Release 3.0

CONTENTS 1
Problem Solving with Algorithms and Data Structures, Release 3.0

2 CONTENTS
CHAPTER

ONE

INTRODUCTION

1.1 Objectives

• To review the ideas of computer science, programming, and problem-solving.


• To understand abstraction and the role it plays in the problem-solving process.
• To understand and implement the notion of an abstract data type.
• To review the Python programming language.

1.2 Getting Started

The way we think about programming has undergone many changes in the years since the first
electronic computers required patch cables and switches to convey instructions from human
to machine. As is the case with many aspects of society, changes in computing technology
provide computer scientists with a growing number of tools and platforms on which to practice
their craft. Advances such as faster processors, high-speed networks, and large memory ca-
pacities have created a spiral of complexity through which computer scientists must navigate.
Throughout all of this rapid evolution, a number of basic principles have remained constant.
The science of computing is concerned with using computers to solve problems.
You have no doubt spent considerable time learning the basics of problem-solving and hope-
fully feel confident in your ability to take a problem statement and develop a solution. You have
also learned that writing computer programs is often hard. The complexity of large problems
and the corresponding complexity of the solutions can tend to overshadow the fundamental
ideas related to the problem-solving process.
This chapter emphasizes two important areas for the rest of the text. First, it reviews the frame-
work within which computer science and the study of algorithms and data structures must fit,
in particular, the reasons why we need to study these topics and how understanding these top-
ics helps us to become better problem solvers. Second, we review the Python programming
language. Although we cannot provide a detailed, exhaustive reference, we will give examples
and explanations for the basic constructs and ideas that will occur throughout the remaining
chapters.

3
Problem Solving with Algorithms and Data Structures, Release 3.0

1.3 What Is Computer Science?

Computer science is often difficult to define. This is probably due to the unfortunate use of
the word “computer” in the name. As you are perhaps aware, computer science is not simply
the study of computers. Although computers play an important supporting role as a tool in the
discipline, they are just that – tools.
Computer science is the study of problems, problem-solving, and the solutions that come out
of the problem-solving process. Given a problem, a computer scientist’s goal is to develop an
algorithm, a step-by-step list of instructions for solving any instance of the problem that might
arise. Algorithms are finite processes that if followed will solve the problem. Algorithms are
solutions.
Computer science can be thought of as the study of algorithms. However, we must be careful to
include the fact that some problems may not have a solution. Although proving this statement
is beyond the scope of this text, the fact that some problems cannot be solved is important for
those who study computer science. We can fully define computer science, then, by including
both types of problems and stating that computer science is the study of solutions to problems
as well as the study of problems with no solutions.
It is also very common to include the word computable when describing problems and solu-
tions. We say that a problem is computable if an algorithm exists for solving it. An alternative
definition for computer science, then, is to say that computer science is the study of problems
that are and that are not computable, the study of the existence and the nonexistence of algo-
rithms. In any case, you will note that the word “computer” did not come up at all. Solutions
are considered independent from the machine.
Computer science, as it pertains to the problem-solving process itself, is also the study of
abstraction. Abstraction allows us to view the problem and solution in such a way as to
separate the so-called logical and physical perspectives. The basic idea is familiar to us in a
common example.
Consider the automobile that you may have driven to school or work today. As a driver, a user
of the car, you have certain interactions that take place in order to utilize the car for its intended
purpose. You get in, insert the key, start the car, shift, brake, accelerate, and steer in order to
drive. From an abstraction point of view, we can say that you are seeing the logical perspective
of the automobile. You are using the functions provided by the car designers for the purpose of
transporting you from one location to another. These functions are sometimes also referred to
as the interface.
On the other hand, the mechanic who must repair your automobile takes a very different point
of view. She not only knows how to drive but must know all of the details necessary to carry
out all the functions that we take for granted. She needs to understand how the engine works,
how the transmission shifts gears, how temperature is controlled, and so on. This is known as
the physical perspective, the details that take place “under the hood.”
The same thing happens when we use computers. Most people use computers to write docu-
ments, send and receive email, surf the web, play music, store images, and play games without
any knowledge of the details that take place to allow those types of applications to work. They
view computers from a logical or user perspective. Computer scientists, programmers, technol-
ogy support staff, and system administrators take a very different view of the computer. They

4 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Figure 1.1: Procedural Abstraction

must know the details of how operating systems work, how network protocols are configured,
and how to code various scripts that control function. They must be able to control the low-level
details that a user simply assumes.
The common point for both of these examples is that the user of the abstraction, sometimes
also called the client, does not need to know the details as long as the user is aware of the way
the interface works. This interface is the way we as users communicate with the underlying
complexities of the implementation. As another example of abstraction, consider the Python
math module. Once we import the module, we can perform computations such as

>>> import math


>>> math.sqrt(16)
4.0
>>>

This is an example of procedural abstraction. We do not necessarily know how the square
root is being calculated, but we know what the function is called and how to use it. If we
perform the import correctly, we can assume that the function will provide us with the correct
results. We know that someone implemented a solution to the square root problem but we only
need to know how to use it. This is sometimes referred to as a “black box” view of a process.
We simply describe the interface: the name of the function, what is needed (the parameters),
and what will be returned. The details are hidden inside (see Figure 1.1).

1.3.1 What Is Programming?

Programming is the process of taking an algorithm and encoding it into a notation, a pro-
gramming language, so that it can be executed by a computer. Although many programming
languages and many different types of computers exist, the important first step is the need to
have the solution. Without an algorithm there can be no program.
Computer science is not the study of programming. Programming, however, is an important
part of what a computer scientist does. Programming is often the way that we create a repre-
sentation for our solutions. Therefore, this language representation and the process of creating
it becomes a fundamental part of the discipline.
Algorithms describe the solution to a problem in terms of the data needed to represent the
problem instance and the set of steps necessary to produce the intended result. Programming
languages must provide a notational way to represent both the process and the data. To this
end, languages provide control constructs and data types.

1.3. What Is Computer Science? 5


Problem Solving with Algorithms and Data Structures, Release 3.0

Control constructs allow algorithmic steps to be represented in a convenient yet unambiguous


way. At a minimum, algorithms require constructs that perform sequential processing, selection
for decision-making, and iteration for repetitive control. As long as the language provides these
basic statements, it can be used for algorithm representation.
All data items in the computer are represented as strings of binary digits. In order to give these
strings meaning, we need to have data types. Data types provide an interpretation for this
binary data so that we can think about the data in terms that make sense with respect to the
problem being solved. These low-level, built-in data types (sometimes called the primitive data
types) provide the building blocks for algorithm development.
For example, most programming languages provide a data type for integers. Strings of binary
digits in the computer’s memory can be interpreted as integers and given the typical meanings
that we commonly associate with integers (e.g. 23, 654, and −19). In addition, a data type also
provides a description of the operations that the data items can participate in. With integers,
operations such as addition, subtraction, and multiplication are common. We have come to
expect that numeric types of data can participate in these arithmetic operations.
The difficulty that often arises for us is the fact that problems and their solutions are very
complex. These simple, language-provided constructs and data types, although certainly suf-
ficient to represent complex solutions, are typically at a disadvantage as we work through the
problem-solving process. We need ways to control this complexity and assist with the creation
of solutions.

1.3.2 Why Study Data Structures and Abstract Data Types?

To manage the complexity of problems and the problem-solving process, computer scientists
use abstractions to allow them to focus on the “big picture” without getting lost in the details.
By creating models of the problem domain, we are able to utilize a better and more efficient
problem-solving process. These models allow us to describe the data that our algorithms will
manipulate in a much more consistent way with respect to the problem itself.
Earlier, we referred to procedural abstraction as a process that hides the details of a particular
function to allow the user or client to view it at a very high level. We now turn our attention to a
similar idea, that of data abstraction. An abstract data type, sometimes called an ADT, is a
logical description of how we view the data and the operations that are allowed without regard
to how they will be implemented. This means that we are concerned only with what the data
is representing and not with how it will eventually be constructed. By providing this level of
abstraction, we are creating an encapsulation around the data. The idea is that by encapsulating
the details of the implementation, we are hiding them from the user’s view. This is called
information hiding.
Figure 1.2 shows a picture of what an abstract data type is and how it operates. The user
interacts with the interface, using the operations that have been specified by the abstract data
type. The abstract data type is the shell that the user interacts with. The implementation is
hidden one level deeper. The user is not concerned with the details of the implementation.
The implementation of an abstract data type, often referred to as a data structure, will require
that we provide a physical view of the data using some collection of programming constructs
and primitive data types. As we discussed earlier, the separation of these two perspectives will

6 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Figure 1.2: Abstract Data Type

allow us to define the complex data models for our problems without giving any indication
as to the details of how the model will actually be built. This provides an implementation-
independent view of the data. Since there will usually be many different ways to implement
an abstract data type, this implementation independence allows the programmer to switch the
details of the implementation without changing the way the user of the data interacts with it.
The user can remain focused on the problem-solving process.

1.3.3 Why Study Algorithms?

Computer scientists learn by experience. We learn by seeing others solve problems and by
solving problems by ourselves. Being exposed to different problem-solving techniques and
seeing how different algorithms are designed helps us to take on the next challenging problem
that we are given. By considering a number of different algorithms, we can begin to develop
pattern recognition so that the next time a similar problem arises, we are better able to solve it.
Algorithms are often quite different from one another. Consider the example of sqrt seen
earlier. It is entirely possible that there are many different ways to implement the details to
compute the square root function. One algorithm may use many fewer resources than another.
One algorithm might take 10 times as long to return the result as the other. We would like to
have some way to compare these two solutions. Even though they both work, one is perhaps
“better” than the other. We might suggest that one is more efficient or that one simply works
faster or uses less memory. As we study algorithms, we can learn analysis techniques that
allow us to compare and contrast solutions based solely on their own characteristics, not the
characteristics of the program or computer used to implement them.
In the worst case scenario, we may have a problem that is intractable, meaning that there is no
algorithm that can solve the problem in a realistic amount of time. It is important to be able
to distinguish between those problems that have solutions, those that do not, and those where
solutions exist but require too much time or other resources to work reasonably.
There will often be trade-offs that we will need to identify and decide upon. As computer
scientists, in addition to our ability to solve problems, we will also need to know and understand

1.3. What Is Computer Science? 7


Problem Solving with Algorithms and Data Structures, Release 3.0

solution evaluation techniques. In the end, there are often many ways to solve a problem.
Finding a solution and then deciding whether it is a good one are tasks that we will do over and
over again.

1.4 Review of Basic Python

In this section, we will review the programming language Python and also provide some more
detailed examples of the ideas from the previous section. If you are new to Python or find that
you need more information about any of the topics presented, we recommend that you consult
a resource such as the Python Language Reference or a Python Tutorial. Our goal here is to
reacquaint you with the language and also reinforce some of the concepts that will be central
to later chapters.
Python is a modern, easy-to-learn, object-oriented programming language. It has a powerful
set of built-in data types and easy-to-use control constructs. Since Python is an interpreted
language, it is most easily reviewed by simply looking at and describing interactive sessions.
You should recall that the interpreter displays the familiar >>> prompt and then evaluates the
Python construct that you provide. For example,

>>> print("Algorithms and Data Structures")


Algorithms and Data Structures
>>>

shows the prompt, the print function, the result, and the next prompt.

1.4.1 Getting Started with Data

We stated above that Python supports the object-oriented programming paradigm. This means
that Python considers data to be the focal point of the problem-solving process. In Python, as
well as in any other object-oriented programming language, we define a class to be a description
of what the data look like (the state) and what the data can do (the behavior). Classes are
analogous to abstract data types because a user of a class only sees the state and behavior of
a data item. Data items are called objects in the object-oriented paradigm. An object is an
instance of a class.

Built-in Atomic Data Types

We will begin our review by considering the atomic data types. Python has two main built-in
numeric classes that implement the integer and floating point data types. These Python classes
are called int and float. The standard arithmetic operations, +, −, *, /, and ** (exponentia-
tion), can be used with parentheses forcing the order of operations away from normal operator
precedence. Other very useful operations are the remainder (modulo) operator, %, and integer
division, //. Note that when two integers are divided, the result is a floating point. The inte-
ger division operator returns the integer portion of the quotient by truncating any fractional part.

8 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Operation Name Operator Explanation


less than < Less than operator
greater than > Greater than operator
less than or equal <= Less than or equal to operator
greater than or equal >= Greater than or equal to operator
equal == Equality operator
not equal =! Not equal operator
logical and and Both operands True for result to be True
logical or or Either operand True for result to be True
logical not not Negates the truth value: False becomes
True, True becomes False

Table 1.1: Relational and Logical Operators

print(2+3*4) #14
print((2+3)*4) #20
print(2**10) #1024
print(6/3) #2.0
print(7/3) #2.33333333333
print(7//3) #2
print(7%3) #1
print(3/6) #0.5
print(3//6) #0
print(3%6) #3
print(2**100) # 1267650600228229401496703205376

The boolean data type, implemented as the Python bool class, will be quite useful for
representing truth values. The possible state values for a boolean object are True and False
with the standard boolean operators, and, or, and not.

>>> True
True
>>> False
False
>>> False or True
True
>>> not (False or True)
False
>>> True and True
True

Boolean data objects are also used as results for comparison operators such as equality (==)
and greater than (>). In addition, relational operators and logical operators can be combined
together to form complex logical questions. Table 1.1 shows the relational and logical
operators with examples shown in the session that follows.

print(5 == 10)
print(10 > 5)

1.4. Review of Basic Python 9


Problem Solving with Algorithms and Data Structures, Release 3.0

Figure 1.3: Variables Hold References to Data Objects

Figure 1.4: Assignment changes the Reference

print((5 >= 1) and (5 <= 10))

Identifiers are used in programming languages as names. In Python, identifiers start with a
letter or an underscore (_), are case sensitive, and can be of any length. Remember that it is
always a good idea to use names that convey meaning so that your program code is easier to
read and understand.
A Python variable is created when a name is used for the first time on the left-hand side of
an assignment statement. Assignment statements provide a way to associate a name with a
value. The variable will hold a reference to a piece of data and not the data itself. Consider the
following session:

>>> the_sum = 0
>>> the_sum
0
>>> the_sum = the_sum + 1
>>> the_sum
1
>>> the_sum = True
>>> the_sum
True

The assignment statement the_sum = 0 creates a variable called the_sum and lets it hold the
reference to the data object 0 (see Figure 1.3). In general, the right-hand side of the assignment
statement is evaluated and a reference to the resulting data object is “assigned” to the name on
the left-hand side. At this point in our example, the type of the variable is integer as that is
the type of the data currently being referred to by “the_sum.” If the type of the data changes
(see Figure 1.4), as shown above with the boolean value True, so does the type of the variable
(the_sum is now of the type boolean). The assignment statement changes the reference being
held by the variable. This is a dynamic characteristic of Python. The same variable can refer to
many different types of data.

10 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Operation Name Operator Explanation


indexing [ ] Access an element of a sequence
concatenation + Combine sequences together
repetition * Concatenate a repeated number of times
membership in Ask whether an item is in a sequence
length len Ask the number of items in the sequence
slicing [ : ] Extract a part of a sequence

Table 1.2: Operations on Any Sequence in Python

Built-in Collection Data Types

In addition to the numeric and boolean classes, Python has a number of very powerful built-
in collection classes. Lists, strings, and tuples are ordered collections that are very similar in
general structure but have specific differences that must be understood for them to be used
properly. Sets and dictionaries are unordered collections.
A list is an ordered collection of zero or more references to Python data objects. Lists are
written as comma-delimited values enclosed in square brackets. The empty list is simply [ ].
Lists are heterogeneous, meaning that the data objects need not all be from the same class and
the collection can be assigned to a variable as below. The following fragment shows a variety
of Python data objects in a list.

>>> [1,3,True,6.5]
[1, 3, True, 6.5]
>>> my_list = [1,3,True,6.5]
>>> my_list
[1, 3, True, 6.5]

Note that when Python evaluates a list, the list itself is returned. However, in order to remember
the list for later processing, its reference needs to be assigned to a variable.
Since lists are considered to be sequentially ordered, they support a number of operations that
can be applied to any Python sequence. Table 1.2 reviews these operations and the following
session gives examples of their use.

Note that the indices for lists (sequences) start counting with 0. The slice operation, my_list[1 :
3], returns a list of items starting with the item indexed by 1 up to but not including the item
indexed by 3.
Sometimes, you will want to initialize a list. This can quickly be accomplished by using
repetition. For example,

>>> my_list = [0] * 6


>>> my_list
[0, 0, 0, 0, 0, 0]

One very important aside relating to the repetition operator is that the result is a repetition
of references to the data objects in the sequence. This can best be seen by considering the

1.4. Review of Basic Python 11


Problem Solving with Algorithms and Data Structures, Release 3.0

Method Name Use Explanation


append a_list.append(item) Adds a new item to the end of a list
insert a_list.insert(i,item) Inserts an item at the 𝑖th position in a list
pop a_list.pop() Removes and returns the last item in a list
pop a_list.pop(i) Removes and returns the 𝑖th item in a list
sort a_list.sort() Modifies a list to be sorted
reverse a_list.reverse() Modifies a list to be in reverse order
del del a_list[i] Deletes the item in the 𝑖th position
index a_list.index(item) Returns the index of the first occurrence of item
count a_list.count(item) Returns the number of occurrences of item
remove a_list.remove(item) Removes the first occurrence of item

Table 1.3: Methods Provided by Lists in Python

following session:

my_list = [1,2,3,4]
A = [my_list]*3
print(A)
my_list[2]=45
print(A)

The variable A holds a collection of three references to the original list called my_list. Note
that a change to one element of my_list shows up in all three occurrences in A.
Lists support a number of methods that will be used to build data structures. Table 1.3 provides
a summary. Examples of their use follow.

my_list = [1024, 3, True, 6.5]


my_list.append(False)
print(my_list)
my_list.insert(2,4.5)
print(my_list)
print(my_list.pop())
print(my_list)
print(my_list.pop(1))
print(my_list)
my_list.pop(2)
print(my_list)
my_list.sort()
print(my_list)
my_list.reverse()
print(my_list)
print(my_list.count(6.5))
print(my_list.index(4.5))
my_list.remove(6.5)
print(my_list)
del my_list[0]
print(my_list)

12 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

You can see that some of the methods, such as pop, return a value and also modify the list.
Others, such as reverse, simply modify the list with no return value. pop will default to
the end of the list but can also remove and return a specific item. The index range starting
from 0 is again used for these methods. You should also notice the familiar “dot” notation
for asking an object to invoke a method. my_list.append(False) can be read as “ask the
object my_list to perform its append method and send it the value False.” Even simple
data objects such as integers can invoke methods in this way.

>>> (54).__add__(21)
75
>>>

In this fragment we are asking the integer object 54 to execute its add method (called __add__
in Python) and passing it 21 as the value to add. The result is the sum, 75. Of course, we usually
write this as 54 + 21. We will say much more about these methods later in this section.
One common Python function that is often discussed in conjunction with lists is the range
function. range produces a range object that represents a sequence of values. By using the
list function, it is possible to see the value of the range object as a list. This is illustrated
below.

>>> range(10)
range(0, 10)
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10)
range(5, 10)
>>> list(range(5,10))
[5, 6, 7, 8, 9]
>>> list(range(5,10,2))
[5, 7, 9]
>>> list(range(10,1,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>>

The range object represents a sequence of integers. By default, it will start with 0. If you
provide more parameters, it will start and end at particular points and can even skip items. In
our first example, range(10), the sequence starts with 0 and goes up to but does not include
10. In our second example, range(5, 10) starts at 5 and goes up to but not including 10.
range(5, 10, 2) performs similarly but skips by twos (again, 10 is not included).
Strings are sequential collections of zero or more letters, numbers and other symbols. We call
these letters, numbers and other symbols characters. Literal string values are differentiated
from identifiers by using quotation marks (either single or double).

>>> "David"
'David'
>>> my_name = "David"
>>> my_name[3]

1.4. Review of Basic Python 13


Problem Solving with Algorithms and Data Structures, Release 3.0

Method Name Use Explanation


center a_string.center(w) Returns a string centered in a field of size 𝑤
count a_string.count(item) Returns the number of occurrences of item
in the string
ljust a_string.ljust(w) Returns a string left-justified in a field of size
𝑤
lower a_string.lower() Returns a string in all lowercase
rjust a_string.rjust(w) Returns a string right-justified in a field of
size 𝑤
find a_string.find(item) Returns the index of the first occurrence of
item
split a_string.split(s_char) Splits a string into substrings at s_char

Table 1.4: Methods Provided by Strings in Python

'i'
>>> my_name*2
'DavidDavid'
>>> len(my_name)
5
>>>

Since strings are sequences, all of the sequence operations described above work as you would
expect. In addition, strings have a number of methods, some of which are shown in Table 1.4.
For example,

>>> my_name
'David'
>>> my_name.upper()
'DAVID'
>>> my_name.center(10)
' David '
>>> my_name.find('v')
2
>>> my_name.split('v')
['Da', 'id']
>>>

Of these, split will be very useful for processing data. split will take a string and return
a list of strings using the split character as a division point. In the example, v is the division
point. If no division is specified, the split method looks for whitespace characters such as tab,
newline and space.
A major difference between lists and strings is that lists can be modified while strings cannot.
This is referred to as mutability. Lists are mutable; strings are immutable. For example, you
can change an item in a list by using indexing and assignment. With a string that change is not
allowed.

14 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

>>> my_list
[1, 3, True, 6.5]
>>> my_list[0]=2**10
>>> my_list
[1024, 3, True, 6.5]
>>> my_name
'David'
>>> my_name[0]='X'
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
my_name[0]='X'
TypeError: 'str' object does not support item assignment
>>>

Note that the error (or traceback) message displayed above is obtained on a Mac OS X machine.
If you are running the above code snippet on a Windows machine, your error output will more
likely be as follows.
>>> my_name[0]='X'
Traceback (most recent call last):
File "<pyshell#84>", line 1, in -toplevel-
my_name[0]='X'
TypeError: object doesn't support item assignment
>>>

Depending on your operating system, or version of Python, the output may slightly vary. How-
ever it will still indicate where and what the error is. You may want to experiment for yourself
and get acquainted with the error message for easier and faster debugging. For the remainder
of this work, we will only display the Mac OS X error messages.
Tuples are very similar to lists in that they are heterogeneous sequences of data. The difference
is that a tuple is immutable, like a string. A tuple cannot be changed. Tuples are written as
comma-delimited values enclosed in parentheses. As sequences, they can use any operation
described above. For example,

>>> my_tuple = (2,True,4.96)


>>> my_tuple
(2, True, 4.96)
>>> len(my_tuple)
3
>>> my_tuple[0]
2
>>> my_tuple * 3
(2, True, 4.96, 2, True, 4.96, 2, True, 4.96)
>>> my_tuple[0:2]
(2, True)
>>>

However, if you try to change an item in a tuple, you will get an error. Note that the error
message provides location and reason for the problem.

1.4. Review of Basic Python 15


Problem Solving with Algorithms and Data Structures, Release 3.0

Operator Use Explanation


in x.in(set) Set membership
len len(set) Returns the cardinality (i.e. the length) of the set
| set1 | set2 Returns a new set with all elements from both sets
& set1 & set2 Returns a new set with only the elements common to both sets
- set1 - set2 Returns a new set with all items from the first set not in second
<= set1 <= set2 Asks whether all elements of the first set are in the second

Table 1.5: Operations on a Set in Python

>>> my_tuple[1]=False
Traceback (most recent call last):
File "<pyshell#137>", line 1, in <module>
my_tuple[1]=False
TypeError: 'tuple' object does not support item assignment
>>>

A set is an unordered collection of zero or more immutable Python data objects. Sets do not
allow duplicates and are written as comma-delimited values enclosed in curly braces. The
empty set is represented by set(). Sets are heterogeneous, and the collection can be assigned
to a variable as below.

>>> {3,6,"cat",4.5,False}
{False, 4.5, 3, 6, 'cat'}
>>> my_set = {3,6,"cat",4.5,False}
>>> my_set
{False, 3, 4.5, 6, 'cat'}
>>>

Even though sets are not considered to be sequential, they do support a few of the familiar
operations presented earlier. Table 1.5 reviews these operations and the following session gives
examples of their use.

>>> my_set
{False, 3, 4.5, 6, 'cat'}
>>> len(my_set)
5
>>> False in my_set
True
>>> "dog" in my_set
False
>>>

Sets support a number of methods that should be familiar to those who have worked with them
in a mathematics setting. Table 1.6 provides a summary. Examples of their use follow. Note
that union, intersection, issubset, and difference all have operators that can be
used as well.

16 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Method Name Use Explanation


union set1.union(set2) Returns a new set with all elements from
both sets
intersection set1.intersection(set2) Returns a new set with only the elements
common to both sets
difference set1.difference(set2) Returns a new set with all items from first set
not in second
issubset set1.issubset(set2) Asks whether all elements of one set are in
the other
add set.add(item) Adds item to the set
remove set.remove(item) Removes item from the set
pop set.pop() Removes an arbitrary element from the set
clear set.clear() Removes all elements from the set

Table 1.6: Methods Provided by Sets in Python

>>> my_set
{False, 3, 4.5, 6, 'cat'}
>>> your_set = {99,3,100}
>>> my_set.union(your_set)
{False, 3, 4.5, 6, 99, 'cat', 100}
>>> my_set | your_set
{False, 3, 4.5, 6, 99, 'cat', 100}
>>> my_set.intersection(your_set)
{3}
>>> my_set & your_set
{3}
>>> my_set.difference(your_set)
{False, 4.5, 6, 'cat'}
>>> my_set - your_set
{False, 4.5, 6, 'cat'}
>>> {3,100}.issubset(your_set)
True
>>> {3,100} <= your_set
True
>>> my_set.add("house")
>>> my_set
{False, 3, 4.5, 6, 'house', 'cat'}
>>> my_set.remove(4.5)
>>> my_set
{False, 3, 6, 'house', 'cat'}
>>> my_set.pop()
False
>>> my_set
{3, 6, 'house', 'cat'}
>>> my_set.clear()
>>> my_set
set()
>>>

1.4. Review of Basic Python 17


Problem Solving with Algorithms and Data Structures, Release 3.0

Operator Use Explanation


[] my_dict[k] Returns the value associated with 𝑘, otherwise its an error
in key in my_dict Returns True if key is in the dictionary, False otherwise
del del my_dict[key] Removes the entry from the dictionary

Table 1.7: Operators Provided by Dictionaries in Python

Our final Python collection is an unordered structure called a dictionary. Dictionaries are
collections of associated pairs of items where each pair consists of a key and a value. This
key-value pair is typically written as key:value. Dictionaries are written as comma-delimited
key:value pairs enclosed in curly braces. For example,

>>> capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'}


>>> capitals
{'Wisconsin': 'Madison', 'Iowa': 'DesMoines'}
>>>

We can manipulate a dictionary by accessing a value via its key or by adding another key-value
pair. The syntax for access looks much like a sequence access except that instead of using the
index of the item we use the key value. To add a new value is similar.

capitals = {'Iowa':'DesMoines','Wisconsin':'Madison'}
print(capitals['Iowa'])
capitals['Utah']='SaltLakeCity'
print(capitals)
capitals['California']='Sacramento'
print(len(capitals))
for k in capitals:
print(capitals[k]," is the capital of ", k)

It is important to note that the dictionary is maintained in no particular order with respect to the
keys. The first pair added ('Utah': 'SaltLakeCity') was placed first in the dictionary
and the second pair added ('California': 'Sacramento') was placed last. The place-
ment of a key is dependent on the idea of “hashing,” which will be explained in more detail
in Chapter 4. We also show the length function performing the same role as with previous
collections.
Dictionaries have both methods and operators. Table 1.7 and Table 1.8 describe them, and the
session shows them in action. The keys, values, and items methods all return objects that
contain the values of interest. You can use the list function to convert them to lists. You
will also see that there are two variations on the get method. If the key is not present in the
dictionary, get will return None. However, a second, optional parameter can specify a return
value instead.

>>> phone_ext={'david':1410, 'brad':1137}


>>> phone_ext
{'brad': 1137, 'david': 1410}
>>> phone_ext.keys() # Returns the keys of the dictionary phone_ext

18 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Method Name Use Explanation


keys my_dict.keys() Returns the keys of the dictionary in a dict_keys
object
values my_dict.values() Returns the values of the dictionary in a
dict_values object
items my_dict.items() Returns the key-value pairs in a dict_items ob-
ject
get my_dict.get(k) Returns the value associated with 𝑘, None other-
wise
get my_dict.get(k,alt) Returns the value associated with 𝑘, 𝑎𝑙𝑡 otherwise

Table 1.8: Methods Provided by Dictionaries in Python

dict_keys(['brad', 'david'])
>>> list(phone_ext.keys())
['brad', 'david']
>>> "brad" in phone_ext
>>> True
>>> 1137 in phone_ext
>>> False # 1137 is not a key in phone_ext
>>> phone_ext.values() # Returns the values of the dictionary
phone_ext
dict_values([1137, 1410])
>>> list(phone_ext.values())
[1137, 1410]
>>> phone_ext.items()
dict_items([('brad', 1137), ('david', 1410)])
>>> list(phone_ext.items())
[('brad', 1137), ('david', 1410)]
>>> phone_ext.get("kent")
>>> phone_ext.get("kent","NO ENTRY")
'NO ENTRY'
>>> del phone_ext["david"]
>>> phone_ext
{'brad': 1137}
>>>

1.4.2 Input and Output

We often have a need to interact with users, either to get data or to provide some sort of result.
Most programs today use a dialog box as a way of asking the user to provide some type of
input. While Python does have a way to create dialog boxes, there is a much simpler function
that we can use. Python provides us with a function that allows us to ask a user to enter some
data and returns a reference to the data in the form of a string. The function is called input.
Python’s input function takes a single parameter that is a string. This string is often called
the prompt because it contains some helpful text prompting the user to enter something. For
example, you might call input as follows:

1.4. Review of Basic Python 19


Problem Solving with Algorithms and Data Structures, Release 3.0

user_name = input('Please enter your name: ')

Now whatever the user types after the prompt will be stored in the user_name variable.
Using the input function, we can easily write instructions that will prompt the user to enter
data and then incorporate that data into further processing. For example, in the following two
statements, the first asks the user for their name and the second prints the result of some simple
processing based on the string that is provided.

user_name = input("Please enter your name ")


print("Your name in all capitals is",user_name.upper(),
"and has length", len(user_name))

It is important to note that the value returned from the input function will be a string
representing the exact characters that were entered after the prompt. If you want this string
interpreted as another type, you must provide the type conversion explicitly. In the statements
below, the string that is entered by the user is converted to a float so that it can be used in
further arithmetic processing.

user_radius = input("Please enter the radius of the circle ")


radius = float(user_radius)
diameter = 2 * radius

String Formatting

We have already seen that the print function provides a very simple way to output values
from a Python program. print takes zero or more parameters and displays them using a single
blank as the default separator. It is possible to change the separator character by setting the
sep argument. In addition, each print ends with a newline character by default. This behavior
can be changed by setting the end argument. These variations are shown in the following
session:

>>> print("Hello")
Hello
>>> print("Hello","World")
Hello World
>>> print("Hello","World", sep="***")
Hello***World
>>> print("Hello","World", end="***")
Hello World***
>>> print("Hello", end="***"); print("World")
Hello***World
>>>

It is often useful to have more control over the look of your output. Fortunately, Python
provides us with an alternative called formatted strings. A formatted string is a template in

20 Chapter 1. Introduction
Problem Solving with Algorithms and Data Structures, Release 3.0

Character Output Format


d,i Integer
u Unsigned Integer
f Floating point as m.ddddd
e Floating point as m.ddddde+/-xx
E Floating point as m.dddddE+/-xx
g Use %e for exponents less than −4 or greater than +5, otherwise us %f
c Single character
s String, or any Python data object that can be converted to a string by using the str
function
% Insert a literal % character

Table 1.9: String Formatting Conversion Characters

which words or spaces that will remain constant are combined with placeholders for variables
that will be inserted into the string. For example, the statement

print(name, "is", age, "years old.")

contains the words is and years old, but the name and the age will change depending on
the variable values at the time of execution. Using a formatted string, we write the previous
statement as

print("%s is %d years old." % (name, age))

This simple example illustrates a new string expression. The % operator is a string operator
called the format operator. The left side of the expression holds the template or format string,
and the right side holds a collection of values that will be substituted into the format string.
Note that the number of values in the collection on the right side corresponds with the number
of % characters in the format string. Values are taken in order, left to right from the collection
and inserted into the format string.
Let’s look at both sides of this formatting expression in more detail. The format string may
contain one or more conversion specifications. A conversion character tells the format opera-
tor what type of value is going to be inserted into that position in the string. In the example
above, the %s specifies a string, while the %d specifies an integer. Other possible type spec-
ifications include i, u, f, e, g, c, or %. Table 1.9 summarizes all of the various type
specifications.
In addition to the format character, you can also include a format modifier between the % and
the format character. Format modifiers may be used to left-justify or right-justify the value
with a specified field width. Modifiers can also be used to specify the field width along with a
number of digits after the decimal point. Table 1.10 explains these format modifiers.
The right side of the format operator is a collection of values that will be inserted into the
format string. The collection will be either a tuple or a dictionary. If the collection is a tuple,
the values are inserted in order of position. That is, the first element in the tuple corresponds
to the first format character in the format string. If the collection is a dictionary, the values
are inserted according to their keys. In this case all format characters must use the (name)

1.4. Review of Basic Python 21


Discovering Diverse Content Through
Random Scribd Documents
together in the narrow shoot, and so the bucket is filled. In the same
way the telescope gathers the rays of light that fall on the object
glass, and condenses them into a small beam which can enter the
eye. We thus have what is nearly equivalent to an eye with a pupil
as big as the object glass. Thus the effect of a grand telescope
amounts to a practical increase of the pupil from the size of a
threepenny-piece up to that of a dinner-plate, or even much larger
still.

THE ASTEROIDS OR SMALL PLANETS.

An asteroid is like a tiny star, and in fact the two bodies are very
often mistaken. If we could get close to the objects, we should see a
wide difference between them. We should find the asteroid to be a
dark planet like our earth, lighted only by the rays from the sun. The
star, small and faint though it may seem, is itself a bright sun, at
such a vast distance that it is only visible as a small point. The star is
millions of times as far from us as the planet, and utterly different in
every respect.
It is a curious fact that the planets should happen to resemble
the stars so closely. We can find an analogous fact in quite another
part of nature. In visiting a good entomological collection, you will
be shown some of the wonderful leaf-like insects. These creatures
have wings, exactly formed to imitate leaves of trees, with the stalks
and veins completely represented. When one of these insects lies at
rest, with its wings folded, among a number of leaves, it would be
almost impossible to penetrate the disguise. This mimicry is no
doubt an ingenious artifice to deceive the birds or other enemies
that want to eat the insect. There is, however, one test which the
cunning bird could apply: the leaves do not move about of their own
accord, but the leaf-insects do. If therefore the bird will only have
the patience to wait, he will see a pair of the seeming leaves move,
and then the deception will be to him a deception no longer, and he
will gobble up the poor insect.
In our attempts to discover the planets we experience just the
same difficulties as the insect-eating bird. Wide as is the true
difference between a planet and a star, there is yet such a seeming
resemblance between them that we are often puzzled to know which
is which. The planets imitate the stars so successfully, that when one
of them is presented to us among myriads of stars it is impossible
for us to detect the planet by its appearance. But we can be cunning
—we can steadily watch, and the moment we find one of these star-
like points beginning to creep about we can pounce upon it. We
know by its movements that it is only disguised as a star, but that it
is really one of the planets.
It is not always easy to discover the asteroids even by this
principle, for unfortunately these bodies move very slowly. If you
have a planet in the field of view, it will creep along so gradually that
an hour or more must have elapsed before it has shifted its position
with respect to the neighboring stars to any appreciable extent. The
search for such little planets is therefore a tedious one, but there are
two methods of conducting it: the new one, which has only recently
come into use, and the old one. I shall speak of the old one first.
Although the body’s motion is so slow, yet when sufficient time
is allowed, the planet will not only move away from the stars close
by, but will even journey round the entire heavens. The surest way
of making the discovery is to study a small part of the heavens now
and to examine the same locality again months or years afterwards.
Memory will not suffice for this purpose. No one could recollect all
the stars he saw with sufficient distinctness to be confident that the
field of the telescope on the second occasion contained either more
or fewer stars than it did on the first. The only way of doing this
work is to draw a map of the stars very carefully. This is a tedious
business, for the stars are so numerous that even in a small part of
the heavens there will be many thousands of stars visible in the
telescope. All of these will have to be entered faithfully in their true
places on the map. When this has been done the map must be laid
aside for a season, and then it is brought out again and compared
with the sky. No doubt the great majority of the objects will be found
just as they were before. These are the stars, the distant suns, and
our concern is not at present with them. Sometimes it will happen
that an object marked on the first map has left a vacant place on the
second. This, however, does not help us much, for, whatever the
object was, it has vanished into obscurity, and a new planet could
hardly be discovered in this way. But sometimes it will happen that
there is a small point of light seen in the second map which has no
corresponding point in the first. Then, indeed, the expectation of the
astronomer is aroused; he may be on the brink of a discovery. Of
course he watches accurately the little stranger. It might be some
star that had been accidentally overlooked when forming the map,
or it might possibly be a star that has become bright in the interval.
But here is a ready test: is the body moving? He looks at it very
carefully, and notes its position with respect to the adjacent stars. In
an hour or two his suspicions may be confirmed; if the object be in
motion, then it is really a planet. A few further observations, made
on subsequent days, will show the path of the body. And the
astronomer has only to assure himself that the object is not one of
the planets that have been already found before he announces his
discovery.
The new method of searching for small planets, which has only
come into use in recent years, is a very beautiful one, and renders
the process of making such discoveries much more easy than the
older method which I have just described.
We can take photographs of the heavenly bodies by adjusting a
sensitive plate in the telescope so that the images of the objects we
desire to see shall fall upon it. The method will apply to very small
stars, if by excellent clockwork and careful guiding we can keep the
telescope constantly pointing to the same spot until the stars have
had time to imprint their little images. Thus we obtain a map of the
heavens, made in a thoroughly accurate manner. Indeed, the
delicacy of photography for this purpose is so great, that the plates
show many stars which cannot be seen with even the greatest of
telescopes. Suppose that a little planet happened to lie among the
stars which are being photographed. All the time that the plate is
being exposed the wanderer is, of course, creeping along, and after
an hour (exposures even longer are often used), it may have moved
through a distance sufficient to ensure its detection. The plate will,
therefore, show the stars as points, but the planet will betray its
presence by producing a streak.
The asteroids now known number between 400 and 500. Out of
this host a few afford some information to the astronomer, but the
majority of them are objects possessing individually only the
slightest interest. No small planet is worth looking at as a telescopic
picture. We should consider that asteroid to be a large one which
possessed a surface altogether as great as England or France. Many
of these planets have a superficial extent not so large as some of
our great counties. A globe which was just big enough to be covered
by Yorkshire—if you could imagine that large county neatly folded
round it—would make a very respectable minor planet.
We know hardly anything of the nature of these small worlds,
but it is certain that any living beings they could support must have
a totally different nature from the creatures that we know on this
earth. We can easily prove this by making a calculation. I shall
suppose a small planet one hundred miles wide, its diameter being,
therefore, the one-eightieth part of the diameter of the earth. If we
were landed on such a globe, we should be far more puzzled by the
extraordinary lightness of everything than we should be in the
similar case of the moon to which I referred (p. 124). If we suppose
the planet to be constructed of materials which had the same
density as those of which the earth is made, then every weight
would be reduced to the eightieth part of what it is here.
There would be one curious consequence of residence on such a
globe. We have heard of attempts to make flying machines, or to
provide a man with wings by which he shall soar aloft like the birds.
All such contrivances have hitherto failed. It may be possible to
make a pair of wings by which a man can fly down, but it is quite
another matter when he tries to fly up again. Suppose, however, we
were living on a small planet, it would be perfectly easy to fly, for as
our bodies would only seem to weigh a couple of pounds, we ought
to be able to flap a pair of wings strong enough to overcome so
trivial a force. I should, however, add that this is on the supposition
that the atmosphere has the same density as our own.
Life on these small planets would indeed be extraordinary. Let us
take, for example, Flora, and see how a game of lawn tennis on that
body would be managed. The very slightest blow of the racket would
drive the ball a prodigious distance before it could touch the ground;
indeed, unless the courts were about half a mile long, it would be
impossible to serve any ball that was not a fault. Nor is there any
great exertion necessary for playing lawn tennis on Flora, even
though the courts are several hundred acres in extent. As a young
lady ran to meet the ball and return it, each of her steps might cover
a hundred yards or so without extra effort; and should she have the
misfortune to get a fall, her descent to the ground would be as
gentle as if she was seeking repose on a bed of the softest swan’s-
down.
These little planets cluster together in a certain part of our
system. Inside are the four inner planets, of which we have already
spoken; outside are the four outer planets, of which we have soon to
speak. Between these two groups there was a vacant space. It
seemed unreasonable that where there was room for planets,
planets should not be found. Accordingly the search was made, and
these objects were discovered. Even at the present day, more and
more are being constantly added to the list.
Up till quite recently all the small planets which had been
discovered confined themselves to the space lying between the
paths of the major planets Mars and Jupiter. This invariable rule was,
however, departed from in the case of one of these bodies which
was discovered in August, 1898. This little body, which was known
for some time by the provisional appellation of D Q, and which has
now been definitely christened Eros, is an exception to this rule. It
travels at an average distance from the sun actually less than that of
Mars, and at the nearest point can come within 15,000,000 miles of
the earth.
We occasionally get information from these little bodies; for in
their revolutions through the solar system, they sometimes pick up
scraps of useful knowledge, which we can elicit from them by careful
examination. For example, one of the most important problems in
the whole of astronomy is to determine the sun’s distance. I have
already mentioned one of the ways of doing this, which is given by
the transit of Venus. Astronomers never like to rely on a single
method; we are therefore glad to discover any other means of
solving the same problem. This it is which the little planets will
sometimes do for us. Juno on one occasion approached very close to
the earth, and astronomers in various parts of the globe observed
her at the same time. When they compared their observations they
measured the sun’s distance. But I am not going to trouble you now
with a matter so difficult. Suffice it to say, that for this, as for all
similar investigations, the observers were constrained to use the
very same principle as that which we illustrated in Fig. 5.
Let me rather close this lecture with the remark that we have
here been considering only the lesser members of the great family
which circulate round the sun, and that we shall speak in our next
lecture of the giant members of our system.
LECTURE IV.
JUPITER, SATURN, URANUS, NEPTUNE.

Jupiter, Saturn, Uranus, Neptune—Jupiter—The Satellites of


Jupiter—Saturn—The Nature of the Rings—William
Herschel—The Discovery of Uranus—The Satellites of
Uranus—The Discovery of Neptune.

Our lecture to-day ought to make us take a very humble view of


the size of our earth. Mercury, Venus, and Mars may be regarded as
the earth’s peers, though we are slightly larger than Venus, and a
good deal larger than Mercury or Mars; but all these four globes are
insignificant in comparison with the gigantic planets which lie in the
outer parts of our system. These great bodies do not enjoy the
benefits of the sun to the same extent that we are permitted to do;
they are so far off that the sun’s rays become greatly enfeebled
before they can traverse the distance; but the gloom of their
situation seems to matter but little, for it is highly improbable that
any of these bodies could be inhabited.
A view of parts of the paths of these four great planets is shown
in Fig. 65. The innermost is Jupiter, which completes a circuit in
about twelve years; then comes Saturn, revolving in an orbit so
great that twenty-nine years and a half are required before the
complete journey is finished. Still further outside is Uranus, which
has a longer journey than Saturn, and moves so much more slowly
that a man would have to live to the ripe old age of eighty-four if a
complete revolution of Uranus was to be accomplished during his
lifetime. At the boundary of our system revolves the planet Neptune,
and though it is a mighty globe, yet we cannot see it without a
telescope. It is invisible to the naked eye for two reasons: first of all,
because it is so far from the sun that the light which illuminates it is
excessively feeble; and, secondly, because it is so far from us that
whatever brilliancy it has is largely reduced.

Fig. 65.—The Orbits of the Four Giant Planets.

JUPITER.

Of all these bodies Jupiter is by far the greatest; he is, indeed,


greater than all the other planets rolled into one. The relative
insignificance of the earth when compared with Jupiter is well
illustrated by the fact that if we took 1200 globes each as big as our
earth, and made them into a single globe, it would only be as large
as the greatest of the planets. A view of the comparative sizes of the
earth and Jupiter is shown in Fig. 66.

Fig. 66.—Jupiter and the Earth compared.

Fig. 67 shows a picture of Jupiter as seen through the telescope.


First, you will notice that the outline of the planet’s shape is not
circular, for it is plain that the vertical diameter in this picture is
shorter than the horizontal one; in fact, Jupiter is flattened at the
Poles and bulges out at the equator, so that a section through the
Poles is an ellipse. Jupiter is turning round rapidly on his axis, and
this will account for the protuberance. We find that the planet has
assumed almost the same form as if it were actually a liquid. This
we can illustrate by a globe of oil which is poised in a mixture of
spirits of wine and water so carefully adjusted that the oil has no
tendency to rise or fall. As we make the globe of oil rotate, which we
can easily do by passing a spindle through it, we see that it bulges
out in the form that Jupiter as well as other planets have taken.
Fig. 67.—The Clouds of Jupiter.

On the picture of the planets you will see shaded bands. These
are constantly changing their aspect, and for a double reason. In the
first place, they change because Jupiter is rotating so quickly that in
five hours the whole side of the planet which is towards us has been
carried out of sight. In another five hours the original side of the
globe will be back again, for the entire rotation occupies about 10
hours, or, more precisely, 9 hours 55 minutes 21 seconds.
But these bands are themselves not permanent objects. They
have no more permanence than the clouds over our own sky.
Sometimes Jupiter’s clouds are more strongly marked than on other
occasions. Sometimes, indeed, they are hardly to be seen at all. It is
from this we learn that those markings which we see when we look
at the great planet are merely the masses of cloud which surround
and obscure whatever may constitute his interior.
There is a circumstance which demonstrates that Jupiter must
be an object exceedingly different from the earth, though both
bodies agree in so far as having clouds are concerned. What would
you think when I tell you that we were able to weigh Jupiter by the
aid of his little moons, of which I shall afterwards speak? These little
bodies inform us that Jupiter is about 300 times as heavy as our
earth, and we have no doubt about this, for it has been confirmed in
other ways. But we have found by actual measurement that Jupiter
is 1200 times as big as the earth, and therefore, if he were
constituted like the earth, he ought to be 1200 times as heavy. This
is, I think, quite plain; for if two cakes were made of the same
material, and one contained twice the bulk of the other, then it
would certainly be twice as heavy. If there be two balls of iron, one
twice the bulk of the other, then, of course, one has twice the weight
of the other. But if a ball of lead have twice the bulk of a ball of iron,
then the leaden ball would be more than twice as heavy as the iron,
because lead is the heavier material. In the same way, the weights
of the earth and Jupiter are not what we might expect from their
relative sizes. If the two bodies were made of the same materials
and in the same state, then Jupiter would be certainly four times as
heavy as we find him to be. We are, therefore, led to the belief that
Jupiter is not a solid body, at least in its outer portions. The masses
of cloud which surround the planet seem to be immensely thick, and
as clouds are, of course, light bodies in comparison with their bulk,
they have the effect of largely increasing the apparent size of
Jupiter, while adding very little to his weight. There is thus a great
deal of mere inflation about this planet, by which he looks much
bigger than his actual materials would warrant if he were constituted
like the earth.
These facts suggest an interesting question. Why has Jupiter
such an immense atmosphere, if we may so call it? The clouds we
are so familiar with down here on the earth are produced by the
heat of the sun, which beats down upon the wide surface of the
ocean, evaporates the water, and raises the vapor up to where it
forms the clouds. Heat, therefore, is necessary for the formation of
cloud; and with clouds so dense and so massive as those on Jupiter,
more heat would apparently be necessary than is required for the
moderate clouds on this earth. Whence is Jupiter to get this heat?
Have we not seen that the great planet is far more distant from the
sun than we are? In fact, the intensity of the sun’s heat on Jupiter is
not more than the twenty-fifth part of what we derive from the same
source. We can hardly believe that the sun supplied the heat to
make those big clouds on the great planet; so we must cast about
for an additional source, which can only be inside the planet itself.
So far as his internal heat is concerned, Jupiter seems to be in much
the same condition now as our earth was once, ages ago, before its
surface had cooled down to the present temperature. As Jupiter is so
much larger than the earth, he has been slower in parting with his
heat. The planet seems not yet to have had time to cool sufficiently
to enable water to remain on his surface. Thus the internal heat of
the planet supplies an explanation of his clouds. We may also
remark that as the present condition of Jupiter illustrates the early
condition of our earth, so the present condition of the earth
foreshadows the future reserved for Jupiter when he shall have had
time to cool down, and when the waters that now exist in the form
of vapor shall be condensed into oceans on his surface.

THE SATELLITES OF JUPITER.

Every owner of a telescope delights to turn it on the planet


Jupiter, both for the spectacle the globe itself affords him, and for a
view of the wonderful system of moons by which the giant planet is
attended. Fortunately the four satellites of Jupiter lie within reach of
even the most modest telescope, and their incessant changes
relative to Jupiter and each other give them a never-ending interest
for the astronomer. Compared with the torpid performance of our
moon, which requires a month to complete a circuit around the
earth, Jupiter’s moons are wonderfully brisk and lively. Nor are they
small bodies like the satellites of Mars, for the second of Jupiter’s
satellites is quite as big as our moon, and the other three are very
much larger. It is, however, true that his satellites appear
insignificant when compared with Jupiter’s own enormous bulk.
The innermost of these little bodies flies right round in a period
of one day and eighteen or nineteen hours, while the outermost of
them takes a little more than a fortnight—that is, rather more than
half the time that our moon demands for a complete revolution.
Jupiter’s satellites are too far off for us to see much with respect to
their structure or appearance even with mighty telescopes. It is, of
course, their great distance from us that makes them look
insignificant. They would, however, be bright enough to be seen like
small stars were it not that, being so close to Jupiter, his
overpowering brightness renders such faint objects in his vicinity
invisible.
It was by means of the satellites of Jupiter that one of the most
beautiful scientific discoveries was made. As a satellite revolves
round the giant planet it often happens that the little body enters
into the shadow of the great planet. No sunlight will then fall upon
the satellite, and as it has no light of its own, it disappears from
sight until it has passed through the shadow and again receives
sunlight on the other side. We can watch these eclipses with our
telescopes, and there can be no more interesting employment for a
small telescope. The movements of these bodies are now known so
thoroughly that the occurrence of the eclipses can be predicted. The
almanacs will tell when the satellite is calculated to disappear, and
when it ought again to return to visibility. When astronomers first
began to make these computations a couple of hundred years ago,
the little satellites gave a great deal of trouble. They would not keep
their time. Sometimes they were a quarter of an hour too soon, and
sometimes a quarter of an hour too late. At last, however, the
reason for these irregularities was discovered, and a wonderful
reason it was.
Suppose there were a number of cannons all over Hyde Park,
and that these cannons were fired at the same moment by
electricity. Though the sounds would all be produced simultaneously,
yet, no matter where you stood, you would not hear them
altogether; the noise from the cannons close at hand would reach
your ears first, and the more distant reports would come in
subsequently. You can calculate the distance of a flash of lightning if
you allow a mile for every five seconds that elapse between the time
you saw the flash and the time you heard the peal of thunder which
followed it. The light and the noise were produced simultaneously,
but the sound takes five seconds to pass over every mile, while the
light, in comparison to sound, may be said to move instantaneously.
That sound travelled with a limited velocity was always obvious, but
never until the discrepancies arose about Jupiter’s satellites was it
learned that light also takes time to travel. It is true that light travels
much more quickly than sound—indeed, about a million times as
fast. Light goes so quickly, that it would rush more than seven times
around the earth in a single second. So far as terrestrial distances
are concerned, the velocity of light is such that the time required for
a journey is inappreciable. The distances, however, between one
celestial body and another are so enormous, that even a ray of light,
moving as quickly as it alone can move, will occupy a measurable
time on the way. Our moon is comparatively so near us, that light
takes little more than a second to cover that short distance. Eight
minutes are, however, required for light to travel from the sun to the
earth; in fact, the sunbeams that now come into our eyes left the
sun eight minutes ago. If the sun were to be suddenly extinguished,
it would still seem to shine as brightly as ever in the eyes of the
inhabitants of this earth for eight minutes longer. As Jupiter is five
times as far from the sun as we are, it follows that the light from the
sun to Jupiter will spend forty minutes on the journey, and the light
from Jupiter to the earth will take a somewhat similar time. When
we look at Jupiter and his moons, we do not see him as he is now,
we see him as he was more than half an hour ago, but the interval
will vary somewhat according to our different distances from the
planet. Sometimes the light from Jupiter will reach us in as little as
thirty-two minutes, while sometimes it will take as much as forty-
eight—that is, the light sometimes requires for its journey a quarter
of an hour more than is sufficient at other times.
We can therefore understand that irregularity of Jupiter’s
satellites which puzzled the early astronomers. An eclipse sometimes
appeared a quarter of an hour before it was expected; because the
earth was then as near as it could be to Jupiter, while the
calculations had been made from observations when Jupiter was at
his greatest distance. It was these eclipses of the satellites which
first suggested the possibility that light must have a measurable
speed. When this was taken into account, then the occasional delay
of the eclipses was found to be satisfactorily explained. Confirmation
flowed in from other sources, and thus the discovery of the velocity
of light was completely established.
Professor Barnard, when studying Jupiter in 1892 with the
splendid refractor at the Lick Observatory, saw a very small point of
light nearer to the planet than the nearest of the four satellites
already known. Further examination showed that this little object
was indeed another satellite. Thus Jupiter has a fifth moon in
addition to the four which have been known so long. This little body
is so small and faint that it can only be discerned under the most
favorable conditions by the most powerful telescopes.

SATURN.

Next outside Jupiter, on the confines of the ancient planetary


system, revolves another grand planet, called Saturn. His distance
from us is sometimes nearly a thousand millions of miles, and he
requires more than a quarter of a century for the completion of each
revolution. Sometimes people do not pronounce the names of the
planets quite correctly. I have heard of a gardener who has a taste
for astronomy, and sometimes begins to talk about the planets
Juniper and Citron. Probably you will know what he meant to say.
The ancients had discovered Saturn to be a planet, for though he
looked like a star, yet his movement through the constellations could
not escape their notice when attention was paid to the heavens.
Fig. 68.—Saturn and the Earth compared.

In the matter of size Saturn is only surpassed by Jupiter among


the planets. He is about 600 times as large as the earth; the small
object, E, shown in Fig. 68, represents our earth in its true
comparative size to the ringed planet; but Saturn is so far off, that
even at his best he is never so bright as Venus, or Mars, or Jupiter
become when they are favorably situated. On the globe of Saturn we
can sometimes see a few bands, but they are faint compared with
those on Jupiter. There is, however, no doubt that what we see upon
Saturn is a dense mass of cloud. Indeed, he can have comparatively
little solid matter inside, for this planet does not weigh so much as a
ball of water the same size would do. Saturn, like Jupiter, must be
highly heated in his interior.
The ring, or rather series of rings, by which the planet is
surrounded are also shown in Fig. 68: these appendages are not
fastened to the globe of Saturn by any material bonds; they are
poised in space, without any support, while the globe or planet
proper is placed symmetrically in the interior.
I have made a model which shows Saturn with his rings, but it is
necessary for me to fasten the rings by little pieces of wire to the
globe, for there is no mechanical means by which the rings of the
model could be poised without support, as they are around the
planet. If we throw the beam of the electric lamp on the little planet,
we see the shadow which the planet casts on its ring. Similar
shadows can be observed in the actual Saturn of the sky, and this is
a proof that the planet does not shine by its own light, but by the
light of the sun which falls upon it. Here again we illustrate the wide
difference between a planet and a star, for were our sun to be put
out, Saturn and all the other planets in the sky would vanish from
sight, while the stars would, of course, twinkle on as before. There
are three rings round Saturn; they all lie in the same plane, and they
are so thin, that when turned edgewise towards us the whole
system almost disappears, except in very powerful telescopes. The
outer and the inner bright rings are divided by a dark line, which can
be traced entirely round. At the inner edge of the inner ring begins
that strange structure called the crape ring, which extends halfway
towards the globe of the planet. The most remarkable point about
the crape ring is its semi-transparency, for we can sometimes see
the globe of the planet through this strange curtain. The crape ring
can only be observed with a powerful telescope. The other two rings
are within the power of very moderate instruments.

THE NATURE OF THE RINGS.

For the explanation of the nature of Saturn’s rings we are


indebted to the calculations of mathematicians. You might have
thought, perhaps, that nothing would be simpler than to suppose
the rings were stiff plates made from solid material. But the question
cannot be thus settled. We know that the ring could not bear the
strain of the planet’s attraction upon it if it were a solid body. I may
illustrate the argument by familiar facts about bridges. Where the
span is but a small one, as, for instance, when a road has to cross a
railway, a canal, or a river, the arch is, of course, the proper kind of
structure. There is, for example, a specially beautiful arch over the
river Dee at Chester. But if the bridge be longer than this, masonry
arches are not suitable. Where a considerable span has to be
crossed, as at the Menai Straits, or a gigantic one, as at the Firth of
Forth, then arches have to be abandoned, and iron bridges of a
totally different construction have to be employed. Arches cannot be
used beyond a limited span, because the strain upon the materials
becomes too great for their powers of resistance to withstand. Each
of the stones in an arch is squeezed by intense pressure, and there
is a limit beyond which even the stoutest stones cannot be relied
upon. As soon, therefore, as the span of the arch is so great that the
stones it contains are squeezed as far as is compatible with safety,
then the limit of size for that form of arch has been reached.
Suppose that you stood on Saturn at his equator, and looked up
at the mighty ring which would stretch edgewise across your sky. It
would rise up from the horizon on one side, and, passing over your
head, would slope down to the horizon on the other. You would, in
fact, be under an arch of which the span was about 100,000 miles.
Owing to the attraction of Saturn, every part of that structure would
be pulled forcibly towards his surface, and thus the materials of the
arch, if it were a solid body, would be compressed with terrific force.
It does not really signify that the arch I am now speaking of is
half of a ring the other half of which is below the globe of the
planet. That is only a difference with respect to the support of two
ends of the arch, and does not affect the question as to the pressure
upon its materials; nor does the fact that the ring is revolving
remove the difficulty, though it undoubtedly lessens it. We know no
solid substance which could endure the pressure. Even the toughest
steel that ever was made would bend up like dough under such
conditions. We cannot, therefore, account for Saturn’s ring by
supposing it to be a solid, for no solid would be strong enough.
Do you not remember the old fable of the oak tree and the
pliant reed—how when the storm was about to arise the oak
laughed at the poor reed, and said it would never be able to
withstand the blasts? But matters did not so turn out. The mighty
oak, which would not yield to the storm, was blown down, while the
slender reed bent to the wind and suffered no injury. This gives us a
hint as to the true constitution of Saturn’s ring; it is not a solid body,
trying to resist by mere strength; it is rather to be explained as an
excessively pliant structure. Indeed, I ought not to call it a structure
at all; it is rather a multitude of small bodies not in the least
attached together. I do not know what the size of these bodies may
be. For anything we can tell, they may be no larger than the pebbles
you find on a gravel walk.
Let us see how we could encircle our earth with rings like those
which surround Saturn. I shall ask you to be provided with a
sufficiently large number of pebbles, and you must also imagine that
I have the means of ascending high up into space, halfway from
here to the moon. Suppose I went up there and simply dropped the
pebble, of course, it would tumble straight down to the earth again.
If, however, I threw it out with proper speed and in the proper
direction, I could start it off like a little moon, and it would go on
round and round our earth in a circle. I mention a pebble, but really
it is little matter what the size of the object may be—it may be as
small as a grain of shot or as big as a cannon-ball. Now take another
pebble. Cast it also in a somewhat similar path, taking care,
however, that the planes of the two orbits shall be the same. Each of
these little bodies shall pursue its journey without interference from
the other. Then proceed in the same way with a third, a fourth, with
thousands and millions and billions of pebbles, until at last the small
bodies will become so numerous that they almost fill a large part of
the plane with a continuous shoal. Each little object, guided entirely
by the earth’s attraction, will pursue its path with undeviating
regularity. Its neighbors will not interfere with it, nor will it interfere
with them. Let us circumscribe the limits of our flat shoal of
moonlets. We first take away all those that lie outside a certain large
circle; then we shall clear away sufficient to make a vacant space
between the outer ring and the inner ring, and thus the two
conspicuous rings have been made; at the inside of the inner ring
we shall take out numbers of pebbles here and there, so as to make
this part much less dense than the outer portions, and thus produce
a semi-transparent crape ring; then we shall clear away those that
come too close to the planet, and form a neat inner boundary.
Could we then view our handiwork from the standpoint of
another planet, what appearance would our earth present? The
several pebbles, though individually so small, would yet, by their
countless numbers, reflect the sun’s light so as to produce the
appearance of a continuous sheet. Thus we should find a large
bright outer ring surrounding the earth, separated by a dark interval
from the inner ring, and at the margin of the inner ring the pebbles
would be so much more sparsely distributed that we should be able
to see through them to some extent. That beautiful system of rings
which Saturn displays is undoubtedly of a similar character to the
hypothetical system which I have endeavored to describe. No other
explanation will account for the facts, especially for the semi-
transparency of the crape ring. The separate bodies from which
Saturn’s rings are constituted seem, however, so small that we are
not able to see them individually. There are some other fine lines
running round the rings beside the great division, and these can also
be explained by the theory I have stated.
Saturn has other claims on our attention besides those of its
rings. It has an elaborate retinue of satellites—no fewer, indeed,
than nine; but some of them are very faint objects, and not by any
means so interesting as the system by which Jupiter is attended.
The ninth of these was discovered quite recently by Professor W. H.
Pickering, of Harvard College Observatory. This little moon, for which
the name “Phoebe” has been suggested, is further from the planet
than any of the others. It is a minute object shining as a star of the
15th or 16th magnitude, and moves around the planet in a period of
about sixteen months.
Saturn was the last and outermost of the planets with which the
ancients were acquainted. Its path lay on the frontiers of the then
known solar system, and the magnificence of the planet itself, with
its attendant luminaries and its marvellous rings, rendered it worthy
indeed of a position so dignified. These five planets—namely,
Mercury, Venus, Mars, Jupiter, and Saturn—made up with the sun
and the moon the seven “planets” of the ancients. They were
supposed to complete the solar system, and, furthermore, the
existence of other members was thought to be impossible. In
modern times it has been discovered that there are yet two more
planets. I do not now refer to those little bodies which run about in
scores between Mars and Jupiter. I mean two grand first-class
planets, far bigger than our earth. One of them is Uranus, which
revolves far outside Saturn, and the other is Neptune, which is much
further still, and whose mighty orbit includes the whole planetary
system in its circuit. To complete its journey round the sun not less
than 165 years is required.

WILLIAM HERSCHEL.

I have to begin the account of this discovery by telling you a


little story. In the middle of the last century there lived at Hanover a
teacher of music whose name was Isaac Herschel. He had a family
of ten children, and he did the best for them that his scanty means
would permit. Of his children William was the fourth, and he
inherited his father’s talents for music, as did most of his brothers
and sisters. He was a bright, clever boy at school, and he made such
good progress in his music that by the time he was fourteen years
old he was able to play in the military band of the Hanoverian
Guards. War broke out between France and England, and as
Hanover was then under the English crown, the French invaded it,
and a battle was fought in which the poor Hanoverian Guards
suffered very terribly. Young Herschel spent the night after the battle
in a ditch, and he came to the conclusion that he did not like
fighting, though he was only a member of the band, and he resolved
to change his profession. That was not so easy to do just then, for
even a bandsman cannot leave the service in war time at his own
free will. William Herschel, however, showed all through his life that
he was not the man to be baffled by difficulties. I do not know
whether he asked for leave, but at all events he took it. He deserted,
in fact, and his friends succeeded in sending him away to England.
He was nineteen years old when he commenced to look for a
career over here, and certainly he found his prospects in the musical
profession very discouraging. Herschel was, however, very
industrious; and at last he succeeded in getting appointed as
organist of the Octagon Chapel at Bath. He gradually became
famous for his musical skill, and had numbers of pupils. He used also
to conduct concerts and oratorios, and was well known in this way
over the West of England. Busy as Herschel was with his profession,
he still retained his love of reading and study. Every moment he
could spare from his duties he devoted to his books. It was natural
that a musician should specially desire to study the theory of music,
and to understand it properly you should know Euclid and algebra,
and, indeed, higher branches of mathematics as well. Herschel did
not know these things at first; he had not the means of learning
them when he was a boy, so he worked very hard after he became a
man. And he studied with such success that he made fair progress in
mathematics, and then it appeared to him that it would be
interesting to learn something about astronomy. After he had begun
to read about the stars, he thought he would like to see them, and
so he borrowed a telescope. It was only a little instrument, but it
delighted him so much that he said he must have one for himself. So
he wrote to London to make inquiries.
Telescopes were much dearer in those days than they are now,
and Herschel could not give the price that the opticians demanded.
Here again his invincible determination came to his aid. What was
there to prevent him from making a telescope? he asked himself;
and forthwith he began the attempt. You will think it strange,
perhaps, that a music-teacher who had no special training as a
mechanic should at once commence so delicate and difficult a task;
but it is not really so hard to make a telescope as might be
imagined. The amateur cannot make such a pretty-looking
instrument as he is able to buy at the shops—the tubes will not be
so beautifully polished and the finish will be such as a trained
workman would be ashamed of—but the essential part of a
telescope is comparatively easy to make; at least, I should say of a
reflecting telescope, which is the kind Herschel attempted to make,
and succeeded in making. You must know that there are two kinds
of telescopes. The commoner one with which you are more familiar
is called the refracting telescope, and it has glass lenses. It was an
instrument constructed on this principle that we spoke of in a former
lecture (p. 97). The reflecting telescope depends for its power upon
a bright mirror at the lower end, and when using this instrument you
look at the reflection of the stars in the mirror. It was a reflector like
this that Herschel began to construct, and he engaged in the task
with enthusiasm. His sister Caroline had come to live with him, and
she used to help him at his work. So much in earnest was he that he
used to rush into his workshop directly he came home from a
concert, and without taking off his best clothes he would plunge into
the grinding and polishing of his mirrors. His sister tried to keep the
house as tidy as possible, but Herschel put up a carpenter’s shop in
the drawing-room, and turning-lathes in the best bedroom. At last
he succeeded. He made a mirror of the right shape, and found that
it exhibited the stars properly. It was not a looking-glass in the
ordinary sense, with glass on one side and quicksilver on the other.
The mirror that Herschel constructed was entirely of metal. It
consisted of a mixture of two parts of copper with one of tin.

Fig. 69.—The Mirror.

The copper has first to be melted in a furnace, for the metal


must be above a red heat before it will begin to run. Then the tin
has to be carefully added, and the casting of the mirror is effected
by pouring the molten metal into a flat mould. Thus the rough mirror
is obtained, which in Herschel’s earlier telescopes seems to have
been about six or seven inches in diameter, and nearly an inch thick.
Though copper is such a tough substance, and though tin is also
tough, yet when melted together to make speculum metal, as this
alloy is called, they produce an exceedingly hard and brittle material.
When we remember that we could never break a copper penny
piece by throwing it down on the flags, it may seem strange that the
“speculum metal” should be so exceedingly brittle. A piece the size
of a penny would be more brittle than a bit of glass of the same
dimensions, and when the speculum is cast, unless it is cooled very
carefully, it will fly into pieces. Herein lay one of the difficulties that
Herschel encountered. Speculum metal must be put into an oven as
soon as the casting has become solid, and then the heat is gradually
allowed to abate. When the speculum has been at last obtained,
next follows the labor of giving it the true figure and polish. It is not
only more fragile than glass, but it is also quite as hard, and
therefore the grinding is a tedious operation. First the surface has to
be ground with coarse sand, and then with emery, which is gradually
made finer and finer until the true figure has been given (Fig. 69).
The mirror is then somewhat basin-shaped, but the depression is
very slight. For example, in a mirror six inches across the depression
at the centre would perhaps be not more than the twentieth of an
inch. Small though this depression is, yet it has to be made with
exactness. In fact, if it were wrong at any point by so much as the
tenth of the thickness of this sheet of paper, the telescope would not
perform accurately. The tool that is used in grinding is made of cast
iron, and has been turned in a lathe to the right shape. It is divided
into squares in the manner shown in Fig. 70. After the grinding
comes the polishing, and this is effected with a tool like the grinder
in shape. This has to be covered over with little squares of pitch, so
that when warmed and put down on the mirror it is soft enough to
receive the right shape. Some rouge and water is spread over the
mirror, and the polisher is worked backward and forward with the
hand until a brilliant surface is obtained.
When the amateur astronomer has
completed this part of the task, all the
great difficulties about his telescope are
conquered. The tube may be made of
wood, and, indeed, a square tube will do
just as well as a round one. He must also
provide for the top of the tube a small
mirror, which has to be perfectly flat. The
preparation of this requires much care,
because it is not so easy as one might Fig. 70.—The Grinding Tool.
suppose to obtain an accurately flat
surface. One way of doing this is to get three pieces, and grind each
two of them together until every pair will touch all over; then they
will certainly all be flat. One more part you want, and that is an
eyepiece. This presents no difficulty. A single glass lens can be made
to answer and your telescope is complete.

THE DISCOVERY OF URANUS.

It was in the year 1774 that Herschel first had a view of the
heavens through the telescope he had himself constructed. During
the early part of his career he does not seem to have made any
important discoveries. He was gradually preparing himself for the
great achievement by which his name became famous.
It was on the 13th of March, 1781, that the organist of the
Octagon Chapel at Bath turned his telescope on the constellation of
the Twins, and began to look at one star after another. You must
know that a star merely looks like a little point in a telescope; even
the greatest instrument will only make a star look brighter, and will
never show it with a perceptible disk. In looking over the stars that
night, Herschel’s attention was arrested by one object that did look
larger when magnified, and therefore was not a star. The only other
objects which would behave in this way were the planets, or possibly
a comet. Indeed, at first Herschel imagined that what he saw must
be a comet. It could hardly have occurred to him that he was to
have such good fortune as to discover a new planet. The five great
planets had been known from all antiquity. Was it reasonable to
suppose that there could be yet another that had never been
perceived? Fortunately, there was a test available. A star remains in
the same place from night to night and from year to year; while a
planet, as we have already had occasion to mention, is a body which
is wandering about. The movements of a planet are, however, not at
all like those of a comet. To decide on the nature of Herschel’s newly
discovered body, it was sufficient to observe the character of its
motion. A few nights sufficed to do this. The position of the body
was carefully marked relatively to the neighboring stars, and it was
soon shown that it was a planet.
Here, then, a great discovery was made. A new planet, now
called Uranus, was added to our system. It would be nothing to
discover a new star. You might as well talk of discovering a new
grain of sand on the seashore. The stars are in untold myriads. They
are so far off that they have no relation whatever to our system,
which is presided over by the sun. But by the detection of a new
planet, revolving far outside Saturn, Herschel showed that a new
and most interesting member had to be added to the five old planets
which have been known from the earliest records of history.
It may well be imagined that a discovery so startling as this
excited astonishment throughout the scientific world. “Who is this
Bath organist?” everybody asked. Accounts of him and his
discoveries appeared in the papers. His fellow-citizens were not so
familiar with the name as we are, happily, now; and the spelling of
the unusual name showed many varieties. When George III. heard
of Herschel’s great achievement, he directed the astronomer to be
summoned to Windsor, that the King might receive an account of the
wonderful discovery from the lips of the discoverer himself. Herschel
of course obeyed, and he brought with him his famous telescope,
and also a map of the whole solar system, to show to the King. No
doubt he thought that his Majesty had probably not paid much
attention to astronomy. Herschel was, therefore, prepared to explain
to the King what it would be necessary for him to know before he
could fully appreciate the magnitude of the discovery.
You will remember that Herschel while still a boy had deserted
from the army, many years previously. It appears that the King had
learned this fact in some way, so that when Herschel was ushered
into his presence his Majesty said that before the great astronomer
could discuss science there was a little matter of business that must
be disposed of. The King accordingly handed Herschel a paper, in
which he was, I dare say, greatly surprised to find a pardon to the
deserter written out by the King himself.
Then Herschel unfolded his wonderful discovery, which the King
thoroughly appreciated, and in the evening the telescope was set up
in the gardens, and the glories of the heavens were displayed.
Herschel made a most favorable impression on his Majesty, and
when the King told the ladies of the Castle next day of all that
Herschel had shown him, their astronomical ardor was also aroused,
and they asked to see through the marvellous tube. Of course
Herschel was ready to comply, and the telescope was accordingly
carried to the windows of the Queen’s apartments at Windsor, which
would have commanded a fine view if the clouds had not been in the
way, which they unfortunately were. Even for royalty the clouds
would not disperse, so what was to be done? Herschel was equal to
the occasion. He specially wanted to exhibit Saturn, for it is one of
the most beautiful objects in the sky, and will fascinate any
intelligent beholder. No astronomers would have been able to see
Saturn through the clouds, but Herschel did not disappoint his
visitors; he directed the instrument, not to the sky (nothing was
there to be seen); he turned it towards a distant garden wall. Now
what would you expect to see by looking through a telescope at a
garden wall—bricks, perhaps, or ivy? What these ladies saw was a
beautiful image of Saturn, his globe in the centre and his rings all
complete, forming so true a resemblance to the planet that even an
experienced astronomer might have been deceived. In the afternoon
Herschel had seen that the clouds were thick, and that there would
be little probability of using the telescope properly. Accordingly he
cut out a little image of Saturn, illuminated it by lamps, and set it up
at a suitable distance on a garden wall.
Herschel’s visit to Windsor was productive of important
consequences. The King said it was a pity that so great an
astronomer should devote himself to music, and that it would be far
better for him to give up that profession and come and live at
Windsor. His Majesty promised that he would pay him a salary, and
he also undertook to provide the cost of erecting great telescopes.
His faithful sister Caroline came with him as his assistant, and also
received some bounty from the King. From that moment Herschel
renounced all his musical business, and devoted himself to his great
life-task of observing the heavens.
He built telescopes of proportions far exceeding those that had
ever been then thought of. He used to stand at night in the open air
from dusk to dawn gazing down the tube of his mighty reflector,
watching the stars and other objects in the heavens as they moved
past. He would dictate what he saw to Caroline, who sat near him. It
was her business to write down his notes and to record the position
of the objects which he was describing. Sometimes, she tells us, the
cold was so great that the ink used to freeze in her pen when she
was at this work. Until he became a very old man, Herschel devoted
himself to his astronomical labors. His discoveries are to be counted
by thousands, though not one of them was so striking or so
important as the detection of the new planet which first brought him
fame.
The question of a name for the addition to the sun’s family had,
of course, to be settled. Herschel had surely a right to be heard at
the christening, and as a compliment to his Majesty he named the
stranger the Georgium Sidus. So, indeed, for a brief while, the planet
was actually styled. The Continental astronomers, however, would
not accept this designation; all the other planets were named after
ancient divinities, and it was thought that the King of England would
seem oddly associated with Jupiter and Saturn; perhaps also they
considered that the British dominions, on which the sun never sets,
were already quite large enough, without further extension to the
celestial regions. Accordingly a consultation was held, the result of
which was that George III. was deprived of his planetary honors,
and the body was given the name of Uranus, which, by universal
consent, it now bears.
The planet Uranus lies just on the verge of visibility with the
unaided eye. It can sometimes be glimpsed like a faint star, and, of
course, with a telescope it is readily perceived. Many generations of
astronomers before Herschel’s time had been observing the heavens,
making maps of the stars, and compiling great catalogues in which
the places of the stars were accurately put down. It often happened
that Uranus came under their notice, but it never occurred to them
that what seemed so like a star was really a planet. I have, no
doubt, said that Uranus looked unlike a star when Herschel
examined it; but then that was because Herschel was a particularly
skilful astronomer. To an observer of a more ordinary type Uranus
would not present any very remarkable appearance, and would be
passed over merely as a small star. In fact, the planet was thus
observed not once or twice, but no fewer than seventeen times,
before the acute eye of Herschel perceived its true character. On
many previous occasions the planet had been noted as a star by
astronomers who are in every way entitled to our respect. It
required a Herschel, determined to see everything in the very best
manner, to grasp the discovery which eluded so many others.
When Uranus was observed on these former occasions and
mistaken for a star, its place had been carefully put down. These
records are at present of the utmost use, because they show the
past history of the planet; and they appear all the more valuable
when we remember that Uranus requires no less than eighty-four
years to accomplish a single revolution around the sun. Thus, since
the planet was discovered in 1781, it had completed one revolution
by 1865, and is now (1899) about one-third of the way around
another. The earlier observations extend backwards almost 200
years, so that altogether we have more or less information about the
movements of the planet during the completion of two circuits and a
half.
Uranus is a great deal bigger than the earth, as you will see in
the view of the comparative sizes of the planets (Fig. 47). It appears
to be of a bluish hue, but we cannot tell whether it turns round on
its axis, or rather, I should say, we are not able to see whether it
turns round on its axis; for we can hardly doubt that it does so.
Notwithstanding that Uranus is at so great a distance from the
earth, we have been able to put this planet, no less than the nearer
ones, in the weighing scales, and we assert with confidence that
Uranus is fifteen times as heavy as our earth. We are indebted to
the satellites for this information.

THE SATELLITES OF URANUS.

You must use a very good telescope to see the satellites of


Uranus. They are four in number, bearing the names of Ariel,
Umbriel, Titania, and Oberon. The innermost of these, Ariel,
completes a journey round the planet in two days and a half;
Oberon, the most distant, requires thirteen days and a half. A planet
is always tending to pull its satellite down, and the satellite is kept
from falling by the speed with which it revolves. The heavier the
planet, the faster must its satellites go round. Thus, to take an
illustration from our own moon, we know that, if the earth were to
be made four times heavier than it is, the moon would have to spin
round twice as fast as it does, in order to remain in the same orbit.
The speed with which the satellites of Uranus revolve accordingly
affords a measure of the mass of the planet. Were Uranus heavier
than he is, his satellites would revolve more quickly than they do;
were he lighter, the satellites would take a longer period to go
round.
Uranus also seems to be greatly swollen by clouds, in the same
manner as are both Jupiter and Saturn; in fact, if our earth was as
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