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

Fundamentals Of Python: Data Structures 2nd Edition Kenneth A. Lambert - eBook PDF download

The document provides information about various eBooks related to Python programming and data structures, including titles by Kenneth A. Lambert and John Canning. It includes links for downloading these eBooks in different formats such as PDF and ePub. Additionally, it contains copyright information and a table of contents for the book 'Fundamentals of Python: Data Structures, 2nd Edition.'

Uploaded by

davenelbeyv2
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)
9 views

Fundamentals Of Python: Data Structures 2nd Edition Kenneth A. Lambert - eBook PDF download

The document provides information about various eBooks related to Python programming and data structures, including titles by Kenneth A. Lambert and John Canning. It includes links for downloading these eBooks in different formats such as PDF and ePub. Additionally, it contains copyright information and a table of contents for the book 'Fundamentals of Python: Data Structures, 2nd Edition.'

Uploaded by

davenelbeyv2
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/ 60

Fundamentals Of Python: Data Structures 2nd

Edition Kenneth A. Lambert - eBook PDF install


download

https://ebookluna.com/download/fundamentals-of-python-data-
structures-ebook-pdf/

Download more ebook from https://ebookluna.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Fundamentals of Python: First Programs, 2nd Edition


Kenneth A. Lambert - eBook PDF

https://ebookluna.com/download/fundamentals-of-python-first-
programs-2nd-edition-ebook-pdf/

ebookluna.com

Data Structures & Algorithms in Python 1st Edition John


Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-in-python-
ebook-pdf-2/

ebookluna.com

Data Structures & Algorithms in Python 1st Edition John


Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-in-python-
ebook-pdf/

ebookluna.com

(eBook PDF) Fundamentals of Python: First Programs 2nd


Edition

https://ebookluna.com/product/ebook-pdf-fundamentals-of-python-first-
programs-2nd-edition/

ebookluna.com
Data Structures - eBook PDF

https://ebookluna.com/download/data-structures-ebook-pdf/

ebookluna.com

(eBook PDF) Principles of Music 2nd Edition by Philip


Lambert

https://ebookluna.com/product/ebook-pdf-principles-of-music-2nd-
edition-by-philip-lambert/

ebookluna.com

(eBook PDF) Introduction to Machine Learning with Python:


A Guide for Data Scientists

https://ebookluna.com/product/ebook-pdf-introduction-to-machine-
learning-with-python-a-guide-for-data-scientists/

ebookluna.com

Data Structures and Applications: A Simple and Systematic


Approach 1st edition - eBook PDF

https://ebookluna.com/download/data-structures-and-applications-a-
simple-and-systematic-approach-ebook-pdf/

ebookluna.com

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 3rd Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-from-
control-structures-through-data-structures-3rd-edition/

ebookluna.com
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
second Edition

Fundamentals of Python:
Data STRUCTURES

Kenneth A. Lambert

Australia • Brazil • Mexico • Singapore • United Kingdom • United States

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.

Important Notice: Media content referenced within the product description or the product
text may not be available in the eBook version.

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Fundamentals of Python: © 2019, 2014 Cengage Learning, Inc.
Data ­Structures, Second Edition
Unless otherwise noted, all content is © Cengage.
Kenneth A. Lambert
ALL RIGHTS RESERVED. No part of this work covered by the
­copyright herein may be reproduced or distributed in any form or
SVP, GM Skills & Global Product by any means, except as permitted by U.S. copyright law, without
Management: Jonathan Lau the prior written permission of the copyright owner.

Product Team Manager: Kristin McNary

Product Manager: Chris Shortt For product information and technology assistance, c­ ontact us
at Cengage Customer & Sales Support,
Product Assistant: Thomas Benedetto
1-800-354-9706 or support.cengage.com.
Executive Director, Content Design: Marah
Bellegarde
For permission to use material from this text or product,
Director, Learning Design: Leigh Hefferon submit all requests online at
www.cengage.com/permissions.
Learning Designer: Kate Mason

Vice President, Strategic Marketing Services:


Jennifer Baker Library of Congress Control Number: 2018956860

Marketing Director: Michele McTighe

Associate Marketing Manager: Cassie Cloutier ISBN: 978-0-357-12275-4

Director, Content Delivery: Patty Stephan


Cengage
Senior Content Manager: Michelle Ruelos
20 Channel Center Street
Cannistraci
Boston, MA 02210
Designer: Erin K. Griffin
USA
Cover image: Digital_Art/Shutterstock.com
Cengage is a leading provider of customized learning solutions with
Service Provider/Compositor: SPi Global employees residing in nearly 40 different countries and sales in
more than 125 countries around the world. Find your local repre-
sentative at www.cengage.com.

Cengage products are represented in Canada by


Nelson Education, Ltd.

To learn more about Cengage platforms and services, register or


access your online learning solution, or purchase m
­ aterials for your
course, visit www.cengage.com.

Notice to the Reader


Publisher does not warrant or guarantee any of the products described herein or perform any independent analysis in c­ onnection
with any of the product information contained herein. Publisher does not assume, and expressly disclaims, any obligation to
obtain and include information other than that provided to it by the manufacturer. The reader is expressly warned to consider
and adopt all safety precautions that might be indicated by the activities described herein and to avoid all potential hazards.
By following the instructions contained herein, the reader willingly assumes all risks in connection with such instructions. The
publisher makes no representations or warranties of any kind, including but not limited to, the warranties of fitness for particular
purpose or merchantability, nor are any such representations implied with respect to the material set forth herein, and the
publisher takes no responsibility with respect to such material. The publisher shall not be liable for any special, consequential, or
exemplary damages resulting, in whole or part, from the readers’ use of, or reliance upon, this material.

Printed in the United States of America


Print Number: 01     Print Year: 2018

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents
iii

Pref ace �������������������������������������������������� xi

CHAPTER 1 B as ic Pyt h o n Programmi ng ��������������������������� 1


Basic Program Elements ��������������������������������������������������� 2
Programs and Modules��������������������������������������������������� 2
An Example Python Program: Guessing a Number��������������� 2
Editing, Compiling, and Running Python Programs��������������� 3
Program Comments ������������������������������������������������������� 4
Lexical Elements������������������������������������������������������������ 4
Spelling and Naming Conventions ������������������������������������ 4
Syntactic Elements��������������������������������������������������������� 5
Literals ������������������������������������������������������������������������ 5
Operators and Expressions ��������������������������������������������� 6
Function Calls ��������������������������������������������������������������� 7
The print Function������������������������������������������������������� 7
The input Function ��������������������������������������������������������� 7
Type Conversion Functions and Mixed-Mode Operations ������ 7
Optional and Keyword Function Arguments ������������������������ 7
Variables and Assignment Statements ������������������������������ 8
Python Data Typing��������������������������������������������������������� 9
import Statements ������������������������������������������������������� 9
Getting Help on Program Components ������������������������������ 9
Control Statements ���������������������������������������������������������10
Conditional Statements��������������������������������������������������10
Using if __name__ == "__main__"�����������������������������11
Loop Statements�����������������������������������������������������������12
Strings and Their Operations ��������������������������������������������12
Operators��������������������������������������������������������������������13
Formatting Strings for Output�����������������������������������������14
Objects and Method Calls�����������������������������������������������15
Built-In Python Collections and Their Operations��������������������16
Lists ��������������������������������������������������������������������������16
Tuples ������������������������������������������������������������������������17

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
contents 

Loops Over Sequences��������������������������������������������������17


Dictionaries �����������������������������������������������������������������18
Searching for a Value�����������������������������������������������������18
Pattern Matching with Collections �����������������������������������18
Creating New Functions ���������������������������������������������������19
iv Function Definitions ������������������������������������������������������19
Recursive Functions������������������������������������������������������20
Nested Function Definitions��������������������������������������������22
Higher-Order Functions��������������������������������������������������23
Creating Anonymous Functions with lambda ���������������������24
Catching Exceptions ��������������������������������������������������������24
Files and Their Operations ������������������������������������������������25
Text File Output������������������������������������������������������������26
Writing Numbers to a Text File ���������������������������������������26
Reading Text from a Text File �����������������������������������������27
Reading Numbers from a File �����������������������������������������28
Reading and Writing Objects with pickle ������������������������29
Creating New Classes ������������������������������������������������������30

CHAPTER 2 An Over view o f Col l ecti ons ������������������������� 37


Collection Types��������������������������������������������������������������38
Linear Collections ��������������������������������������������������������38
Hierarchical Collections��������������������������������������������������39
Graph Collections ���������������������������������������������������������39
Unordered Collections���������������������������������������������������40
Sorted Collections��������������������������������������������������������40
A Taxonomy of Collection Types��������������������������������������40
Operations on Collections��������������������������������������������������41
Fundamental Operations on All Collection Types�����������������41
Type Conversion�����������������������������������������������������������43
Cloning and Equality �����������������������������������������������������43
Iterators and Higher-Order Functions�����������������������������������44
Implementations of Collections������������������������������������������44

CHAPTER 3 Search in g , ­S o r ti ng, and Compl ex i ty Anal y si s��� 49


Measuring the Efficiency of Algorithms��������������������������������50
Measuring the Run Time of an Algorithm ��������������������������50
Counting Instructions�����������������������������������������������������53
Measuring the Memory Used by an Algorithm��������������������55
Complexity Analysis ���������������������������������������������������������55
Orders of Complexity�����������������������������������������������������56
Big-O Notation��������������������������������������������������������������57
The Role of the Constant of Proportionality�����������������������58
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
 contents

Search Algorithms �����������������������������������������������������������59


Search for the Minimum ������������������������������������������������59
Sequential Search of a List ��������������������������������������������60
Best-Case, Worst-Case, and Average-Case Performance�����60
Binary Search of a Sorted List ���������������������������������������61
Comparing Data Items ��������������������������������������������������62 v
Basic Sort Algorithms ������������������������������������������������������64
Selection Sort��������������������������������������������������������������64
Bubble Sort �����������������������������������������������������������������65
Insertion Sort ��������������������������������������������������������������67
Best-Case, Worst-Case, and Average-Case Performance
Revisited��������������������������������������������������������������������68
Faster Sorting��������������������������������������������������������������69
Overview of Quicksort ���������������������������������������������������70
Merge Sort������������������������������������������������������������������74
An Exponential Algorithm: Recursive Fibonacci ��������������������77
Converting Fibonacci to a Linear Algorithm�����������������������78

CHAPTER 4 Ar r ays an d Linked Structures ���������������������� 89


The Array Data Structure��������������������������������������������������90
Random Access and Contiguous Memory��������������������������92
Static Memory and Dynamic Memory��������������������������������93
Physical Size and Logical Size ���������������������������������������94
Operations on Arrays��������������������������������������������������������94
Increasing the Size of an Array���������������������������������������95
Decreasing the Size of an Array��������������������������������������95
Inserting an Item into an Array That Grows �����������������������96
Removing an Item from an Array��������������������������������������97
Complexity Trade-Off: Time, Space, and Arrays�����������������98
Two-Dimensional Arrays (Grids) �����������������������������������������99
Processing a Grid������������������������������������������������������� 100
Creating and Initializing a Grid��������������������������������������� 100
Defining a Grid Class��������������������������������������������������� 101
Ragged Grids and Multidimensional Arrays ��������������������� 101
Linked Structures ���������������������������������������������������������� 102
Singly Linked Structures and Doubly Linked Structures ���� 103
Noncontiguous Memory and Nodes ������������������������������� 104
Defining a Singly Linked Node Class������������������������������ 106
Using the Singly Linked Node Class ������������������������������ 106
Operations on Singly Linked Structures ���������������������������� 108
Traversal ������������������������������������������������������������������ 108
Searching������������������������������������������������������������������ 109
Replacement ������������������������������������������������������������� 110
Inserting at the Beginning��������������������������������������������� 111
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
contents 

Inserting at the End ���������������������������������������������������� 111


Removing at the Beginning ������������������������������������������ 112
Removing at the End��������������������������������������������������� 113
Inserting at Any Position���������������������������������������������� 114
Removing at Any Position��������������������������������������������� 116
vi Complexity Trade-Off: Time, Space, and Singly Linked
Structures ��������������������������������������������������������������� 116
Variations on a Link ������������������������������������������������������� 118
A Circular Linked Structure with a Dummy Header Node��� 118
Doubly Linked Structures��������������������������������������������� 119

CHAPTER 5  In t er f aces , ­I m pl ementati ons,


an d Po lym o r phi sm���������������������������������� 126
Developing an Interface ������������������������������������������������� 127
Designing the Bag Interface������������������������������������������ 127
Specifying Arguments and Return Values������������������������ 129
Constructors and Implementing Classes ��������������������������� 130
Preconditions, Postconditions, Exceptions,
and Documentation ��������������������������������������������������� 131
Coding an Interface in Python��������������������������������������� 132
Developing an Array-Based Implementation������������������������ 134
Choose and Initialize the Data Structures������������������������ 134
Complete the Easy Methods First ��������������������������������� 135
Complete the Iterator ������������������������������������������������� 136
Complete the Methods That Use the Iterator ������������������ 137
The in Operator and the __contains__ Method������������ 137
Complete the remove Method��������������������������������������� 138
Developing a Link-Based Implementation��������������������������� 139
Initialize the Data Structures ���������������������������������������� 139
Complete the Iterator ������������������������������������������������� 140
Complete the Methods clear and add��������������������������� 140
Complete the Method remove��������������������������������������� 141
Run-Time Performance of the Two Bag Implementations ������ 142
Testing the Two Bag Implementations ������������������������������� 142
Diagramming the Bag Resource with UML ������������������������� 144

CHAPTER 6 In h er it an ce an d Abstract Cl asses��������������� 148


Using Inheritance to Customize an Existing Class��������������� 149
Subclassing an Existing Class��������������������������������������� 150
Revising the __init__ Method ������������������������������������ 150
Adding a New __contains__ Method ��������������������������� 152
Modifying the Existing add Method ������������������������������� 152
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
 contents

Modifying the Existing __add__ Method ������������������������ 153


Run-Time Performance of ArraySortedBag ������������������ 153
A Note on Class Hierarchies in Python ��������������������������� 154
Using Abstract Classes to Eliminate Redundant Code ��������� 155
Designing an AbstractBag Class��������������������������������� 155
Redoing the __init__ Method in AbstractBag ������������ 157 vii
Modifying the Subclasses of AbstractBag��������������������� 157
Generalizing the __add__ Method in AbstractBag��������� 158
An Abstract Class for All Collections��������������������������������� 159
Integrating AbstractCollection into the Collection
Hierarchy ���������������������������������������������������������������� 159
Using Two Iterators in the __eq__ Method ��������������������� 161
A Professional-Quality Framework of Collections ���������������� 162

CHAPTER 7 St ack s ������������������������������������������������� 167


Overview of Stacks��������������������������������������������������������� 168
Using a Stack ��������������������������������������������������������������� 169
The Stack Interface ���������������������������������������������������� 169
Instantiating a Stack ��������������������������������������������������� 170
Example Application: Matching Parentheses ������������������� 171
Three Applications of Stacks������������������������������������������� 174
Evaluating Arithmetic Expressions��������������������������������� 174
Evaluating Postfix Expressions ������������������������������������� 175
Converting Infix to Postfix ������������������������������������������� 176
Backtracking ������������������������������������������������������������� 179
Memory Management��������������������������������������������������� 181
Implementations of Stacks ��������������������������������������������� 184
Test Driver ���������������������������������������������������������������� 184
Adding Stacks to the Collection Hierarchy���������������������� 185
Array Implementation��������������������������������������������������� 186
Linked Implementation ������������������������������������������������ 187
The Role of the Abstract Stack Class ���������������������������� 190
Time and Space Analysis of the Two Implementations ������ 191

C HAPTER 8 Qu eu es ������������������������������������������������� 205


Overview of Queues ������������������������������������������������������� 206
The Queue Interface and Its Use��������������������������������������� 207
Two Applications of Queues��������������������������������������������� 210
Simulations ��������������������������������������������������������������� 210
Round-Robin CPU Scheduling ��������������������������������������� 212
Implementations of Queues��������������������������������������������� 213
A Linked Implementation of Queues������������������������������� 213
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
contents 

An Array Implementation ��������������������������������������������� 215


Time and Space Analysis for the Two Implementations������ 217
Priority Queues ������������������������������������������������������������� 226

CHAPTER 9 Lis t s ���������������������������������������������������� 239


viii Overview of Lists ���������������������������������������������������������� 240
Using Lists ������������������������������������������������������������������� 240
Index-Based Operations������������������������������������������������ 241
Content-Based Operations ������������������������������������������� 242
Position-Based Operations ������������������������������������������� 242
Interfaces for Lists������������������������������������������������������ 247
Applications of Lists ������������������������������������������������������ 249
Heap-Storage Management ������������������������������������������ 249
Organization of Files on a Disk ������������������������������������� 250
Implementation of Other Collections������������������������������ 252
List Implementations������������������������������������������������������ 252
The Role of the AbstractList Class ��������������������������� 252
An Array-Based Implementation ������������������������������������ 254
A Linked Implementation ��������������������������������������������� 255
Time and Space Analysis for the Two Implementations������ 258
Implementing a List Iterator��������������������������������������������� 260
Role and Responsibilities of a List Iterator ��������������������� 260
Setting Up and Instantiating a List Iterator Class������������� 261
The Navigational Methods in the List Iterator ������������������ 262
The Mutator Methods in the List Iterator ������������������������ 263
Design of a List Iterator for a Linked List������������������������ 264
Time and Space Analysis of List Iterator
Implementations ������������������������������������������������������� 265
Recursive List Processing ���������������������������������������������� 270
Basic Operations on a Lisp-Like List������������������������������ 271
Recursive Traversals of a Lisp-Like List ������������������������� 272
Building a Lisp-Like List������������������������������������������������ 273
The Internal Structure of a Lisp-Like List������������������������ 275
Printing Lisp-Like Lists in IDLE with __repr__���������������� 276
Lists and Functional Programming��������������������������������� 277

CHAPTER 10 Trees ���������������������������������������������������� 282


An Overview of Trees������������������������������������������������������ 283
Tree Terminology�������������������������������������������������������� 283
General Trees and Binary Trees ������������������������������������ 284
Recursive Definitions of Trees��������������������������������������� 285
Why Use a Tree?������������������������������������������������������������ 286
The Shape of Binary Trees ���������������������������������������������� 288

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
 contents

Binary Tree Traversals ��������������������������������������������������� 291


Preorder Traversal������������������������������������������������������ 291
Inorder Traversal��������������������������������������������������������� 291
Postorder Traversal ���������������������������������������������������� 292
Level Order Traversal��������������������������������������������������� 292
Three Common Applications of Binary Trees ���������������������� 293 ix
Heaps����������������������������������������������������������������������� 293
Binary Search Trees ��������������������������������������������������� 293
Expression Trees��������������������������������������������������������� 295
Developing a Binary Search Tree ������������������������������������� 297
The Binary Search Tree Interface ���������������������������������� 297
Data Structure for the Linked Implementation������������������ 299
Complexity Analysis of Binary Search Trees ������������������� 304
Recursive Descent Parsing and Programming
Languages������������������������������������������������������������������ 304
Introduction to Grammars��������������������������������������������� 305
Recognizing, Parsing, and Interpreting Sentences
in a Language ���������������������������������������������������������� 306
Lexical Analysis and the Scanner ���������������������������������� 307
Parsing Strategies������������������������������������������������������ 307
An Array Implementation of Binary Trees��������������������������� 313
Implementing Heaps ������������������������������������������������������ 315

CHAPTER 11 Set s an d Dict ionari es������������������������������� 322


Using Sets ������������������������������������������������������������������� 323
The Python Set Class������������������������������������������������������ 324
A Sample Session with Sets������������������������������������������ 325
Applications of Sets ��������������������������������������������������� 325
Relationship Between Sets and Bags������������������������������ 325
Relationship Between Sets and Dictionaries ������������������� 326
Implementations of Sets���������������������������������������������� 326
Array-Based and Linked Implementations of Sets ��������������� 326
The AbstractSet Class ��������������������������������������������� 327
The ArraySet Class��������������������������������������������������� 328
Using Dictionaries ��������������������������������������������������������� 329
Array-Based and Linked Implementations of Dictionaries������ 330
The Entry Class��������������������������������������������������������� 330
The AbstractDict Class ������������������������������������������� 331
The ArrayDict Class������������������������������������������������� 333
Complexity Analysis of the Array-Based and Linked
Implementations of Sets and Dictionaries��������������������� 334
Hashing Strategies��������������������������������������������������������� 335

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
contents 

The Relationship of Collisions to Density������������������������ 336


Hashing with Nonnumeric Keys ������������������������������������� 337
Linear Probing������������������������������������������������������������ 339
Quadratic Probing ������������������������������������������������������ 340
Chaining ������������������������������������������������������������������� 341
x Complexity Analysis ���������������������������������������������������� 342
Hashing Implementation of Sets��������������������������������������� 349
Hashing Implementation of Dictionaries ���������������������������� 352
Sorted Sets and Dictionaries ������������������������������������������ 354

CHAPTER 12 Gr aph s ������������������������������������������������� 359


Why Use Graphs? ���������������������������������������������������������� 360
Graph Terminology��������������������������������������������������������� 360
Representations of Graphs ��������������������������������������������� 364
Adjacency Matrix��������������������������������������������������������� 365
Adjacency List������������������������������������������������������������ 366
Analysis of the Two Representations������������������������������ 367
Further Run-Time Considerations ���������������������������������� 368
Graph Traversals������������������������������������������������������������ 369
A Generic Traversal Algorithm��������������������������������������� 369
Breadth-First and Depth-First Traversals������������������������� 370
Graph Components������������������������������������������������������ 372
Trees Within Graphs������������������������������������������������������� 373
Spanning Trees and Forests������������������������������������������ 373
Minimum Spanning Tree����������������������������������������������� 373
Algorithms for Minimum Spanning Trees ������������������������ 373
Topological Sort������������������������������������������������������������ 376
The Shortest-Path Problem ��������������������������������������������� 377
Dijkstra’s Algorithm ���������������������������������������������������� 377
The Initialization Step ������������������������������������������������� 377
The Computation Step ������������������������������������������������ 379
Representing and Working with Infinity��������������������������� 380
Analysis��������������������������������������������������������������������� 380
Floyd’s Algorithm ������������������������������������������������������� 380
Analysis��������������������������������������������������������������������� 382
Developing a Graph Collection ���������������������������������������� 382
Example Use of the Graph Collection����������������������������� 383
The Class LinkedDirectedGraph������������������������������� 384
The Class LinkedVertex ������������������������������������������� 388
The Class LinkedEdge������������������������������������������������ 390

Glo s s ar y �����������������������������������������������������401

In dex ���������������������������������������������������� 410


Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Preface
xi

Welcome to Fundamentals of Python: Data Structures, 2nd Edition. This text is intended
for a second semester course in programming and problem solving with data structures. It
covers the material taught in a typical Computer Science 2 course (CS2) at the undergradu-
ate level. Although this book uses the Python programming language, you need only have a
basic knowledge of programming in a high-level programming language before beginning
Chapter 1.

What You’ll Learn


The book covers four major aspects of computing:
1. Programming basics—Data types, control structures, algorithm development,
and program design with functions are basic ideas that you need to master to solve
problems with computers. You’ll review these core topics in the Python program-
ming language and employ your understanding of them to solve a wide range of
problems.
2. Object-Oriented Programming (OOP)—Object-Oriented Programming is the
dominant programming paradigm used to develop large software systems. You’ll
be introduced to the fundamental principles of OOP so that you can apply them
­successfully. Unlike other textbooks, this book helps you develop a professional-
quality framework of collection classes to illustrate these principles.
3. Data structures—Most useful programs rely on data structures to solve prob-
lems. At the most concrete level, data structures include arrays and various types
of linked structures. You’ll use these data structures to implement various types of
collection structures, such as stacks, queues, lists, trees, bags, sets, dictionaries, and
graphs. You’ll also learn to use complexity analysis to evaluate the space/time trade-
offs of different implementations of these collections.
4. Software development life cycle—Rather than isolate software development tech-
niques in one or two chapters, this book deals with them throughout in the context
of numerous case studies. Among other things, you’ll learn that coding a program
is often not the most difficult or challenging aspect of problem solving and software
development.

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P r e fa c e Why Python?

Why Python?
Computer technology and applications have become increasingly more sophisticated over
the past three decades, and so has the computer science curriculum, especially at the intro-
ductory level. Today’s students learn a bit of programming and problem solving and are
then expected to move quickly into topics like software development, complexity analysis,
xii
and data structures that, 30 years ago, were relegated to advanced courses. In addition,
the ascent of object-oriented programming as the dominant paradigm has led instructors
and textbook authors to bring powerful, industrial-strength programming languages such
as C++ and Java into the introductory curriculum. As a result, instead of experiencing the
rewards and excitement of solving problems with computers, beginning computer science
students often become overwhelmed by the combined tasks of mastering advanced con-
cepts as well as the syntax of a programming language.
This book uses the Python programming language as a way of making the second course
in computer science more manageable and attractive for students and instructors alike.
Python has the following pedagogical benefits:
•• Python has simple, conventional syntax. Python statements are very close to those of
pseudocode algorithms, and Python expressions use the conventional notation found
in algebra. Thus, you can spend less time dealing with the syntax of a programming
­language and more time learning to solve interesting problems.
•• Python has safe semantics. Any expression or statement whose meaning violates the
definition of the language produces an error message.
•• Python scales well. It is easy for beginners to write simple programs in Python. Python
also includes all the advanced features of a modern programming language, such as
­support for data structures and object-oriented software development, for use when
they become necessary, especially in the second course in computer science
•• Python is highly interactive. You can enter expressions and statements at an interpreter’s
prompts to try out experimental code and receive immediate feedback. You can also
compose longer code segments and save them in script files to be loaded and run as
modules or stand-alone applications.
•• Python is general purpose. In today’s context, this means that the language includes
resources for contemporary applications, including media computing and web
services.
•• Python is free and is in widespread use in the industry. You can download Python to run
on a variety of devices. There is a large Python user community, and expertise in Python
programming has great resume value.
To summarize these benefits, Python is a comfortable and flexible vehicle for ­expressing
ideas about computation, both for beginners and for experts. If you learn these ideas well
in the first year, you should have no problems making a quick transition to other lan-
guages needed for courses later in the curriculum. Most importantly, you will spend less
time staring at a computer screen and more time thinking about interesting problems
to solve.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Organization of this Book P r e fa c e

Organization of this Book


The approach in this book is easygoing, with each new concept introduced only when it is
needed.
Chapter 1 provides a review of the features of Python programming that are needed to begin
a second course in programming and problem solving in Python. The content of this chapter xiii
is organized so that you can skim it quickly if you have experience in Python programming,
or you can dig a bit deeper to get up to speed in the language if you are new to Python.
Chapters 2 through 12 covers the major topics in a typical CS2 course, especially the specifica-
tion, implementation, and application of abstract data types, with the collection types as the
primary vehicle and focus. Along the way, you will be thoroughly exposed to object-oriented
programming techniques and the elements of good software design. Other important CS2 topics
include recursive processing of data, search and sort algorithms, and the tools used in software
development, such as complexity analysis and graphical notations (UML) to document designs.
Chapter 2 introduces the concept of an abstract data type (ADT) and provides an overview
of various categories of collection ADTs.
Chapters 3 and 4 explore the data structures used to implement most collections and the
tools for analyzing their performance trade-offs. Chapter 3 introduces complexity analysis
with big-O notation. Enough material is presented to enable you to perform simple analyses
of the running time and memory usage of algorithms and data structures, using search and
sort algorithms as examples. Chapter 4 covers the details of processing arrays and linear
linked structures, the concrete data structures used to implement most collections. You’ll
learn the underlying models of computer memory that support arrays and linked structures
and the time/space trade-offs that they entail.
Chapters 5 and 6 shift the focus to the principles of object-oriented design. These principles
are used to organize a professional-quality framework of collection classes that will be cov-
ered in detail in later chapters.
Chapter 5 is concerned with the critical difference between interface and implementation.
A single interface and several implementations of a bag collection are developed as a first
example. Emphasis is placed on the inclusion of conventional methods in an interface, to
allow different types of collections to collaborate in applications. For example, one such
method creates an iterator, which allows you to traverse any collection with a simple loop.
Other topics covered in this chapter include polymorphism and information hiding, which
directly stem from the difference between interface and implementation.
Chapter 6 shows how class hierarchies can reduce the amount of redundant code in an object-
oriented software system. The related concepts of inheritance, dynamic binding of method
calls, and abstract classes are introduced here and used throughout the remaining chapters.
Armed with these concepts and principles, you’ll then be ready to consider the other major
collection ADTs, which form the subject of Chapters 7 through 12.
Chapters 7 through 9 present the linear collections, stacks, queues, and lists. Each collec-
tion is viewed first from the perspective of its users, who are aware only of an interface and
a set of performance characteristics possessed by a chosen implementation. The use of each
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P r e fa c e Special Features

collection is illustrated with one or more applications, and then several implementations
are developed, and their performance trade-offs are analyzed.
Chapters 10 through 12 present advanced data structures and algorithms as a transition to
later courses in computer science. Chapter 10 discusses various tree structures, including
binary search trees, heaps, and expression trees. Chapter 11 examines the ­implementation
xiv of the unordered collections, bags, sets, and dictionaries, using hashing strategies.
­Chapter 12 introduces graphs and graph-processing algorithms.
As mentioned earlier, this book is unique in presenting a professional-quality framework of
collection types. Instead of encountering a series of apparently unrelated collections, you
will explore the place of each collection in an integrated whole. This approach allows you
to see what the collection types have in common as well as what makes each one unique.
At the same time, you will be exposed to a realistic use of inheritance and class hierarchies,
topics in object-oriented software design that are difficult to motivate and exemplify at this
level of the curriculum.

Special Features
This book explains and develops concepts carefully, using frequent examples and diagrams.
New concepts are then applied in complete programs to show how they aid in solving prob-
lems. The chapters place an early and consistent emphasis on good writing habits and neat,
readable documentation.
The book includes several other important features:
•• Case studies—These present complete Python programs ranging from the simple to the
substantial. To emphasize the importance and usefulness of the software development life
cycle, case studies are discussed in the framework of a user request, followed by analysis,
design, implementation, and suggestions for testing, with well-defined tasks performed at
each stage. Some case studies are extended in end-of-chapter programming projects.
•• Chapter summaries—Each chapter after the first one ends with a summary of the
major concepts covered in the chapter.
•• Key terms—When a new term is introduced in the text, it appears in bold face.
­Definitions of the key terms are also collected in a glossary.
•• Exercises—Most major sections of each chapter after the first one end with exercise
questions that reinforce the reading by asking basic questions about the material in the
section. After Chapter 2, each chapter ends with review questions.
•• Programming projects—Each chapter ends with a set of programming projects of
varying difficulty.

New in this Edition


The most obvious change in this edition is the addition of full color. All program examples
include the color coding used in Python’s IDLE, so students can easily identify program
elements such as keywords, comments, and function, method, and class names. Learning
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Instructor Resources P r e fa c e

objectives have been added to the beginning of each chapter. Several new figures have been
added to illustrate concepts, and many programming projects have been added or reworked.
A new section on iterators and higher-order functions has been added to Chapter 2. Finally,
a new section on Lisp-like lists, recursive list processing, and functional programming has
been added to Chapter 9.
xv
Instructor Resources
MindTap
MindTap activities for Fundamentals of Python: Data Structures are designed to help stu-
dents master the skills they need in today's workforce. Research shows employers need
critical thinkers, troubleshooters, and creative problem-solvers to stay relevant in our
fast-paced, technology-driven world. MindTap helps you achieve this with assignments
and activities that provide hands-on practice and real-life relevance. Students are guided
through assignments that help them master basic knowledge and understanding before
moving on to more challenging problems.
All MindTap activities and assignments are tied to defined unit learning objectives. H
­ ands-on
coding labs provide real-life application and practice. Readings and dynamic visualizations
support the lecture, while a post-course assessment measures exactly how much a class
stands in terms of progress, engagement, and completion rates. Use the content and learning
path as-is, or pick and choose how our materials will wrap around yours. You control what
the students see and when they see it. Learn more at http://www.cengage.com/mindtap/.

Instructor Companion Site


The following teaching tools are available for download at the Companion Site for this text.
Go to instructor.cengage.com and sign in to the instructor account. Search for the textbook
and add the text to the instructor dashboard.
•• Instructor’s Manual: The Instructor’s Manual that accompanies this textbook includes
additional instructional material to assist in class preparation, including items such as
­Overviews, Chapter Objectives, Teaching Tips, Quick Quizzes, Class Discussion Topics,
Additional Projects, Additional Resources, and Key Terms. A sample syllabus is also available.
•• Test Bank: Cengage Testing Powered by Cognero is a flexible, online system that allows
you to:
•• author, edit, and manage test bank content from multiple Cengage solutions
•• create multiple test versions in an instant
•• deliver tests from your LMS, your classroom, or wherever you want
•• PowerPoint Presentations: This text provides PowerPoint slides to accompany each
chapter. Slides may be used to guide classroom presentations, to make available to stu-
dents for chapter review, or to print as classroom handouts. Files are provided for every
figure in the text. Instructors may use the files to customize PowerPoint slides, illustrate
quizzes, or create handouts.
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
P r e fa c e Dedication

•• Solutions: Solutions to all programming exercises are available. If an input file is


needed to run a programming exercise, it is included with the solution file.
•• Source Code: The source code is available at www.cengage.com. If an input file is
needed to run a program, it is included with the source code.

xvi

The first-of-its-kind digital subscription designed specially to lower costs. Students get total
access to everything Cengage has to offer on demand—in one place. That’s 20,000 eBooks,
2,300 digital learning products, and dozens of study tools across 70 disciplines and over
675 courses. Currently available in select markets. Details at www.cengage.com/unlimited

We Appreciate Your Feedback


We have tried to produce a high-quality text, but should you encounter any errors, please report
them to [email protected]. A listing of errata, should they be found, as well as other informa-
tion about the book, will be posted on the website http://home.wlu.edu/~lambertk/python/.

Acknowledgments
I would like to thank my friend, Martin Osborne, for many years of advice, friendly
­criticism, and encouragement on several of my book projects.
I would also like to thank my students in Computer Science 112 at Washington and Lee
University for classroom testing this book over several semesters.
Finally, I would like to thank Kristin McNary, Product Team Manager; Chris Shortt, Product
Manager; Maria Garguilo and Kate Mason, Learning Designers; Magesh Rajagopalan, Senior
Project Manager; Danielle Shaw, Tech Editor; and especially Michelle Ruelos Cannistraci,
Senior Content Manager, for ­handling all the details of producing this edition of the book.

About the Author


Kenneth A. Lambert is a professor of computer science and the chair of that department
at Washington and Lee University. He has taught introductory programming courses for
over 30 years and has been an active researcher in computer science education. Lambert
has authored or coauthored a total of 28 textbooks, including a series of introductory C++
­textbooks with Douglas Nance and Thomas Naps, a series of introductory Java textbooks
with Martin Osborne, and a series of introductory Python textbooks.

Dedication
To Brenda Wilson, with love and admiration.
Kenneth A.­Lambert
Lexington, VA
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1
Basic Python
Programming

After completing this chapter, you will be able to:

Write a simple Python program using its basic structure


Perform simple input and output operations
Perform operations with numbers such as arithmetic and
comparisons
Perform operations with Boolean values
Implement an algorithm using the basic constructs of
sequences of statements, selection statements, and loops
Define functions to structure code
Use built-in data structures such as strings, files, lists,
tuples, and dictionaries
Define classes to represent new types of objects
Structure programs in terms of cooperating functions,
data structures, classes, and modules

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1 Basic Python Programming

This chapter gives a quick overview of Python programming. It is intended to bring those
new to or rusty in Python up to speed, but it does not pretend to be a thorough introduc-
tion to computer science or the Python programming language. For a more detailed treat-
ment of programming in Python, see my book Fundamentals of Python: First Programs,
Second Edition (Cengage Learning, 2019). For documentation on the Python programming
2
language, visit www.python.org.
If your computer already has Python, check the version number by running the python
or python3 command at a terminal prompt. (Linux and Mac users first open a terminal
­window, and Windows users first open a DOS window.) You are best off using the most
current version of Python available. Check for that at www.python.org, and download and
install the latest version if necessary. You will need Python 3.0 or higher to run the pro-
grams presented in this book.

Basic Program Elements


Like all contemporary programming languages, Python has a vast array of features and
constructs. However, Python is among the few languages whose basic program ele-
ments are quite simple. This section discusses the essentials to get you started in Python
programming.

Programs and Modules


A Python program consists of one or more modules. A module is just a file of Python code,
which can include statements, function definitions, and class definitions. A short Python
program, also called a script, can be contained in one module. Longer, more complex pro-
grams typically include one main module and one or more supporting modules. The main
module contains the starting point of program execution. Supporting modules contain
function and class definitions.

An Example Python Program: Guessing a Number


Next, you’ll see a complete Python program that plays a game of guess-the-number with
the user. The computer asks the user to enter the lower and upper bounds of a range of
numbers. The computer then “thinks” of a random number in that range and repeatedly
asks the user to guess this number until the user enters a correct guess. The computer gives
a hint to the user after each guess and displays the total number of guesses at the end of the
process. The program includes several of the types of Python statements to be discussed
later in this chapter, such as input statements, output statements, assignment statements,
loops, and conditional statements. The program also includes a single function definition.
Here is the code for the program, in the file numberguess.py:
"""
Author: Ken Lambert
Plays a game of guess the number with the user.
"""

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Basic Program Elements

import random

def main():
"""Inputs the bounds of the range of numbers
and lets the user guess the computer’s number until
the guess is correct."""
smaller = int(input("Enter the smaller number: ")) 3
larger = int(input("Enter the larger number: "))
myNumber = random.randint(smaller, larger)
count = 0
while True:
count += 1
userNumber = int(input("Enter your guess: "))
if userNumber < myNumber:
print("Too small")
elif userNumber > myNumber:
print("Too large")
else:
print("You’ve got it in", count, "tries!")
break

if __name__ == "__main__":
main()

Here is a trace of a user’s interaction with the program:


Enter the smaller number: 1
Enter the larger number: 32
Enter your guess: 16
Too small
Enter your guess: 24
Too large
Enter your guess: 20
You’ve got it in 3 tries!

Note that the code and its trace appear in the colors black, blue, orange, and green. Python’s
IDLE uses color coding to help the reader recognize various types of program elements.
The role of each color will be explained shortly.

Editing, Compiling, and Running Python Programs


You can run complete Python programs, including most of the examples presented, by
entering a command in a terminal window. For example, to run the program contained in
the file numberguess.py, enter the following command in most terminal windows:
python3 numberguess.py

To create or edit a Python module, try using Python’s IDLE (short for Integrated
­DeveLopment Environment). To start IDLE, enter the idle or idle3 command at a terminal
prompt or launch its icon if it is available. You can also launch IDLE by double-clicking on
a Python source code file (any file with a .py extension) or by right-clicking on the file and

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1 Basic Python Programming

selecting Open or Edit with IDLE. Make sure that your system is set to open IDLE when
files of this type are launched (this is the default on macOS but not on Windows).
IDLE gives you a shell window for interactively running Python expressions and statements.
Using IDLE, you can move back and forth between editor windows and the shell window to
develop and run complete programs. IDLE also formats your code and color-codes it.
4
When you open an existing Python file with IDLE, the file appears in an editor window, and
the shell pops up in a separate window. To run a program, move the cursor into the editor
window and press the F5 (function-5) key. Python compiles the code in the editor window
and runs it in the shell window.
If a Python program appears to hang or not quit normally, you can exit by pressing Ctrl+C
or closing the shell window.

Program Comments
A program comment is text ignored by the Python compiler but valuable to the reader as
documentation. An end-of-line comment in Python begins with a # symbol and extends to
the end of the current line. It is color-coded in red. For example:
# This is an end-of-line comment.

A multiline comment is a string enclosed in triple single quotes or triple double quotes.
Such comments, which are colored green, are also called docstrings, to indicate that they
can document major constructs within a program. The numberguess program shown
­earlier includes two doc strings. The first one, at the top of the program file, serves as a
comment for the entire numberguess module. The second one, just below the header of the
main function, describes what this function does. As we shall see shortly, docstrings play a
critical role in giving help to a programmer within the Python shell.

Lexical Elements
The lexical elements in a language are the types of words or symbols used to construct
­sentences. As in all high-level programming languages, some of Python’s basic symbols are
keywords, such as if, while, and def, which are colored orange. Also included among lexical
items are identifiers (names), literals (numbers, strings, and other built-in data structures),
operators, and delimiters (quotation marks, commas, parentheses, square brackets, and
braces). Among the identifiers are the names of built-in functions, which are colored purple.

Spelling and Naming Conventions


Python keywords and names are case-sensitive. Thus, while is a keyword, whereas While
is a programmer-defined name. Python keywords are spelled in lowercase letters and are
color-coded in orange in an IDLE window.

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Basic Program Elements

All Python names, other than those of built-in functions, are color-coded in black, except
when they are introduced as function, class, or method names, in which case they appear
in blue. A name can begin with a letter or an underscore (_), followed by any number of
­letters, underscores, or digits.
In this book, the names of modules, variables, functions, and methods are spelled in lower-
case letters. With the exception of modules, when one of these names contains one or more 5
embedded words, the embedded words are capitalized. The names of classes follow the
same conventions but begin with a capital letter. When a variable names a constant, all the
letters are uppercase, and an underscore separates any embedded words. Table 1-1 shows
examples of these naming conventions.

Type of Name Examples


Variable salary, hoursWorked, isAbsent

Constant ABSOLUTE_ZERO, INTEREST_RATE

Function or method printResults, cubeRoot, input

Class BankAccount, SortedSet

Table 1-1 Examples of Python Naming Conventions

Use names that describe their role in a program. In general, variable names should
be nouns or adjectives (if they denote Boolean values), whereas function and method
names should be verbs if they denote actions, or nouns or adjectives if they denote values
returned.

Syntactic Elements
The syntactic elements in a language are the types of sentences (expressions, statements,
definitions, and other constructs) composed from the lexical elements. Unlike most high-
level languages, Python uses white space (spaces, tabs, or line breaks) to mark the syntax
of many types of sentences. This means that indentation and line breaks are significant in
Python code. A smart editor like Python’s IDLE can help indent code correctly. The pro-
grammer need not worry about separating sentences with semicolons and marking blocks
of sentences with braces. In this book, I use an indentation width of four spaces in all
Python code.

Literals
Numbers (integers or floating-point numbers) are written as they are in other program-
ming languages. The Boolean values True and False are keywords. Some data structures,
such as strings, tuples, lists, and dictionaries, also have literals, as you will see shortly.

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 1 Basic Python Programming

String Literals
You can enclose strings in single quotes, double quotes, or sets of three double quotes or
three single quotes. The last notation is useful for a string containing multiple lines of text.
Character values are single-character strings. The \ character is used to escape nongraphic
characters such as the newline (\n) and the tab (\t), or the \ character itself. The next code
6 segment, followed by the output, illustrates the possibilities.
print("Using double quotes")
print('Using single quotes')
print("Mentioning the word ‘Python’ by quoting it")
print("Embedding a\nline break with \\n")
print("""Embedding a
line break with triple quotes""")

Output:
Using double quotes
Using single quotes
Mentioning the word 'Python' by quoting it
Embedding a
line break with \n
Embedding a
line break with triple quotes

Operators and Expressions


Arithmetic expressions use the standard operators (+, –, *, /, %) and infix notation. The
/ operator produces a floating-point result with any numeric operands, whereas the //
­operator produces an integer quotient. The + operator means concatenation when used
with collections, such as strings and lists. The ** operator is used for exponentiation.
The comparison operators <, <=, >, >=, ==, and != work with numbers and strings.
The == operator compares the internal contents of data structures, such as two lists, for
structural equivalence, whereas the is operator compares two values for object identity.
Comparisons return True or False.
The logical operators and, or, and not treat several values, such as 0, None, the empty string,
and the empty list, as False. In contrast, most other Python values count as True.
The subscript operator, [], used with collection objects, will be examined shortly.
The selector operator, ‘ ’, is used to refer to a named item in a module, class, or object.

The operators have the standard precedence (selector, function call, subscript, arithmetic,
comparison, logical, assignment). Parentheses are used in the usual manner, to group sub-
expressions for earlier evaluation.
The ** and = operators are right associative, whereas the others are left associative.

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Basic Program Elements

Function Calls
Functions are called in the usual manner, with the function’s name followed by a parenthe-
sized list of arguments. For example:
min(5, 2) # Returns 2

Python includes a few standard functions, such as abs and round. Many other functions are 7
available by import from modules, as you will see shortly.

The print Function


The standard output function print displays its arguments on the console. This function
allows a variable number of arguments. Python automatically runs the str function on each
argument to obtain its string representation and separates each string with a space before
output. By default, print terminates its output with a newline.

The input Function


The standard input function input waits for the user to enter text at the keyboard. When the
user presses the Enter key, the function returns a string containing the characters entered.
This function takes an optional string as an argument and prints this string, ­without a line
break, to prompt the user for the input.

Type Conversion Functions and Mixed-Mode Operations


You can use some data type names as type conversion functions. For example, when the
user enters a number at the keyboard, the input function returns a string of digits, not a
numeric value. The program must convert this string to an int or a float before numeric
processing. The next code segment inputs the radius of a circle, converts this string to a
float, and computes and outputs the circle’s area:

radius = float(input("Radius: "))


print("The area is", 3.14 * radius ** 2)

Like most other languages, Python allows operands of different numeric types in arithmetic
expressions. In those cases, the result type is the same type as the most general operand
type. For example, the addition of an int and a float produces a float as the result.

Optional and Keyword Function Arguments


Functions may allow optional arguments, which can be named with keywords when the
function is called. For example, the print function by default outputs a newline after

Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-200-203
Copyright 2019 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Other documents randomly have
different content
CHAPTER XII
THE GREAT SECRET

J ust as I thought this, wonderful to relate, the door was pushed


wholly open, and there stood master. His face was on fire—all lit
up by his blazing eyes.
Mrs. Wasp rose pretty quickly to her feet, although master had
seemed to take no note of her excitement.
“I’ve got such news,” he said, “I couldn’t wait to be announced.
Stanna, I’ve got a son—a little son.”
“A baby,” she screamed—“impossible—you’re dreaming,” and she
went up to him, and shook him.
“It’s true, true,” he said, and he stared at Mr. Bonstone who had
grasped his hand and was shaking it heartily.
“Take your hat off, take your hat off,” ejaculated Mrs. Bonstone, and
her husband helping her, they pushed my dear master into the
middle chair by the fire, and sat down each side of him.
Here he was at home in the heart of his friends, and one of them he
had seen only once before. But that made no difference. If Mr.
Bonstone had had a brother, he could not have surveyed him more
affectionately than he was surveying my dear master.
I was licking his shoes, his hands—I was nearly crazy with delight,
and even Gringo and Walter Scott were grinning.
“Now, tell us all about it,” said Mrs. Wasp, clapping her hands, “but
first, are you hungry? You look as pale as a ghost. When did you last
have something to eat?”
“I don’t know,” said master faintly.
“The bell, Norman,” she said. “Quick now, Jeannie,” she said to the
maid who appeared almost instantaneously; “a tray right here—
soup, tea and toast, for the present. In two hours we will have
supper in the dining-room—chicken salad, cold meats, hot rolls,
anything else nice that cook can get us.”
Master, who was listening, murmured, “How very kind you are,
Stanna.”
“No, Rudolph, not kind,” she said sweetly. “Just returning some of
your many attentions to a tiresome girl. Now, tell us about it—tell us.
You’re quite sure about the baby, you’re not deluded—that would be
too cruel.”
“I’ve seen it, handled it,” said master starting up in his chair and
pushing his hair back from his forehead with both hands—a trick he
had when he was greatly excited. “It’s a beauty.”
“Boy or girl?” cried Stanna.
“Boy.”
“And Clossie—tell us about her. I thought she was so very ill.”
“She has been. She is worn to a shadow. Her flesh is gone——”
“Clossie thin!” ejaculated Mrs. Bonstone.
“As a wraith. I scarcely knew her. She hid her face from me, the poor
child. She cried—she thinks she is disfigured for life. She, the mother
of my child. I tell you, she’s glorious—absolutely glorious. I never
saw a more beautiful woman.”
Mrs. Bonstone exchanged a glance with her husband. Master was
frightfully excited. Then she passed a hand over her forehead.
That was a hint to her husband not to excite their friend, and the
poor man had never opened his lips. Ladies are queer, even the best
of them.
To cap the climax, she said, “Norman, you mustn’t stimulate
Rudolph. You two are to be good friends, and will have plenty of
time to talk bye and bye.”
Mr. Bonstone gave her one of his speaking glances, then as master
was breaking again into animated speech, he said, briefly, “You’re
done out. Rest for a bit. I’m going to get you a drop of stimulant,”
and he with his wife vanished from the room.
Left alone with me, for Gringo and Walter Scott with exquisite dog
propriety had followed their owners, master gave me the whole
story.
“Come up, Boy,” he said patting his knees, and I jumped up.
It seems he had rushed to a train in the morning, reached the
country place where the hospital is situated, and driven rapidly
there.
A smiling nurse had led him to a room where there were ever so
many baby cots all tagged and numbered. She showed him one
lovely, weeny child tagged Granton. Master nearly went crazy. He
couldn’t, and wouldn’t, believe at first that it was his, and the head
physician explained, that after consultation with master’s own
physician in New York, they had decided to gratify Mrs. Granton,
who had wished to surprise her husband, and not let him know that
a baby was coming to her. It was unusual, the doctor said, but it had
to be done, as they feared for her reason, if they deceived her.
“Take me to her, take me to her,” said my master. “I forgive the
deception. The mother of my child can do no wrong.”
At first he had great trouble. She longed to see him, yet did not
want to. There was a great change in her appearance. Finally, after
sending message after message, he prevailed upon her to let him
pay a five-minute call.
He did not tell me everything just here, but I knew by what he did
say, that dear mistress had lost all her pretty looks, and yet now she
was more attractive than ever in his eyes.
“It’s the soul shining through, Boy, that counts,” he said with tears in
his eyes. “She is a madonna now.”
When was the baby coming home, that is what I wanted to know,
but I did not find out till the Bonstones came back in the room.
Mistress and young master were to return home in three weeks.
“And the baby’s name?” asked Mrs. Bonstone, when master was
taking his soup and looking much refreshed.
Master dropped his spoon. “There’s only one name in this country
good enough for my boy,” he said intensely.
“Oh! George Washington, of course,” she replied. “I might have
known.”
After master took his soup and crackers, or “biscuits,” as Walter
Scott calls them, he simply collapsed with fatigue. He couldn’t wait
for supper.
You see he had been up all the night before in the cathedral, but he
did not tell them this. Even with one’s best friends, I notice, human
beings have reticences.
“I tell you everything, Boy,” said master to me afterward, “for you
can’t repeat. If dogs could talk, they would not be such valuable
friends to us.”
Mr. Bonstone was just going to take master upstairs, and put him to
bed, when to the amazement of the men, Mrs. Bonstone began to
cry.
“Stanna,” said her husband in a frightened way.
“I want a baby,” she said in a choked voice.
They stared at her, and so did we three dogs.
“Perhaps, if you wait,” said master kindly.
“I want one to-night,” she said mopping her eyes. “There are so
many poor little babies without a home—unhappy little creatures,
crying in the night. I want to adopt one.”
Mr. Bonstone, as if he were telling her he would go down town and
buy her a present, said, “Wait till I come downstairs. I’ll get you
one.”
She threw herself in a big chair, and cried harder than ever. I think
she was overwrought, and was having a spell of nerves. I followed
my master and Mr. Bonstone upstairs.
“Look here, Bonstone,” said my master, “it isn’t so easy to pick up a
baby at a minute’s notice. You’d better put her off till to-morrow.”
“She’s got to have it to-night,” said he, pressing his thin lips together
in his inflexible way.
“There are all kinds of difficulties,” continued my master, “signing
contracts, proving life support and legacy after your death, giving
references and so on.”
“There are babies ready to jump into a home,” said Mr. Bonstone.
“I have it,” exclaimed master as he sat on the edge of the bed, in a
magnificent guest room. “Go to old Ellen, I’ll give you her address,
and take my dog. He’ll lead you to her apartment.”
This just suited me. I hadn’t been out all day, except for my little
walk before dinner, and I jumped and fawned round Mr. Bonstone.
“Who is she?” he inquired in his short way.
Master explained how much he thought of her, and even wrote her a
note, introducing Mr. Bonstone.
“Does she know?” inquired Mr. Bonstone.
“About the baby?” said my master with a heavenly smile. “She was
the first one to get a telegram.”
Mr. Bonstone didn’t understand this, but I did. Old Ellen would be in
the seventh heaven, and Robert Lee and Beanie would be half way
there.
I danced downstairs, and danced up to Mrs. Bonstone, and she let
her handkerchief fall on the floor like a little damp cobweb. Then she
sniffed, and asked her husband to lend her his.
He took out his big one for her, then he telephoned for a taxi-cab.
“If you let the baby get cold, I’ll never forgive you,” said Mrs.
Bonstone.
“It won’t get cold,” he said, and seizing her satin, fur-trimmed cloak,
he doubled it all up, and put it under his arm.
Gringo wanted to come too, but Mr. Bonstone said, “Go back, your
face might frighten it.”
Gringo wasn’t very well pleased, though he saw the wisdom of this
remark. I often had long arguments with him about the bulldog
visage. I claimed that bulldogs, Boston terriers, any dogs with lay-
back noses and undershot jaws, were displeasing and terrifying to
timid human beings. Give me a dog with a good facial expression,
and a head not running all to jaws. Of course, I loved Gringo
because he was my friend, but I would rather have had him a long-
headed, amiable-looking fellow, if I’d been making him.
I scampered down the steps and out-of-doors like the wind, and was
waiting by the taxi when Mr. Bonstone came. One would have
thought that his wife would have accompanied him on so important
a quest, but strange to say she did not seem to want to come, and
Gringo, who heard her talking to herself after we left, said that her
staying behind was a bit of feminine mother-wit. She wanted a little
poor child to make it happy. There was no doubt of her loving it, but
she wasn’t so sure of her husband. If he chose it, he would be more
interested, and if at any time he found fault with the child, she could
say, “Why, it was your choice.”
It didn’t take us very long to get to old Ellen’s avenue, which was
quite bright and lively, but her flat was dark and quiet, when we
mounted the long stairs. She had evidently gone to bed.
Mr. Bonstone had a hard time to find the bell, for, as he was not a
smoker, he did not carry matches. After a long time of ringing,
Robert Lee appeared and asked drowsily what was wanted.
As Mr. Bonstone spoke to him, he flashed me a glance of
recognition, then went to his mother’s bed-room, where Beanie was
barking lustily.
Mr. Bonstone and I entered, and he sat in Ellen’s rocker while I ran
to greet Beanie, and talk over the joyful news with him. The dog
was, as I thought he would be, wild with delight.
“I want to see it—I want to see it,” he said over and over, and I
promised that by hook or by crook, I would manage so that he
might see this little baby of his dearly loved mistress.
“I should think you’d be jealous,” I said. “Mistress will never want
you home again, if she has a baby to play with.”
He looked thoughtful, but he said bravely, “I can’t help that. The
main thing is to have her happy.”
“Beanie,” I said, “you are a much better dog than I thought you
were, when I first knew you.”
“I guess troubles improve one,” he said, “and I feel better since I
lost my flesh.”
“Too much fat is bad for dog or man,” I said, then I ran to old Ellen
who was coming in dressed in her neat cotton wrapper, and looking
as calm as if she was used to being routed out of her bed every
night of her life.
Mr. Bonstone explained his errand, and her face lighted up. “If
you’se a friend of my dear Mister Granton,” she said, “old Ellen will
do anything she can for you.” Then she wrinkled her brow. She was
doing some thinking.
“Would your lady take a little dark child?” she asked.
“Do you mean a coloured child?” he said.
“Oh, no, sir,” and she smiled; “no, no—I mean dark like Sicilian or
Syrian. I know a Syrian baby—”
“Good healthy child?” asked Mr. Bonstone.
“Yes, sir—a monstrous fine child, and not so very dark complected—
but considerable darker than you.”
“I’ll go telephone,” said Mr. Bonstone, with what for him, was quite
an amount of eagerness.
He got out of the room so quickly, that I could not follow him. In a
few minutes he came back smiling. “My wife says she doesn’t care
what the shade is—to bring it quickly.”
“I’ll go first, sir,” said Ellen, “it’s close by,” and she stepped out into
the hall, and crossing to a near by flat, knocked on a door and went
in.
After some time she came back, and asked Mr. Bonstone to follow
her. I pushed after him, for this was wildly interesting to me. I took
good care, though, to keep in the background, lest I should be
driven out.
This other flat reminded me of the nests of boxes ladies buy—one
box inside another, and another inside that, till you get to the tiniest
box. It seems a Syrian family renting it, took boarders, and at first it
was quite an effort to single out the various members of the various
families.
They all looked respectable and fairly clean, but they were certainly
very crowded. I think they were all peddlers of fruit and vegetables
or trinkets. There was a roaring coal fire in a kitchen stove, and they
all sat round it. One man was playing on a queer-looking musical
instrument, and the others were listening to him. One big girl had a
baby in her arms. This probably was the baby Ellen had spoken of,
and I looked at it anxiously.
It was a healthy, happy-looking little object in a ragged, but not too
dirty frock.
Ellen motioned to this girl, and she followed us into an inner room,
or rather a closet, where a young woman with a dark, eager face lay
on a tiny bed. It was a poor place, and smelt stuffy, but not unclean.
I knew by the girl’s face she was the baby’s mother. Oh! what a
devouring glance she gave Mr. Bonstone.
He said never a word, but opening his coat, took a picture from his
pocket and laid it before her. That was Mrs. Bonstone, I knew. I
could imagine how the picture of this pretty, rich young woman
impressed this sick, poor young woman.
The young woman’s eye just burnt into the photograph. That
probably was what she would like to be, and here she was laid up
with an injured back, Ellen told us, suffering untold torture most of
the time, and likely to die any hour.
She was not related to the other persons in the house. She was
merely boarding with them. Her young husband had died while on
the way to this country, and she had been struck by a trolley car a
few days before, and knew she must die and leave her baby.
Her anxiety was frightful, yet there was a kind of comfort in it for
her, for she gazed from Ellen, whom she knew, to Mr. Bonstone
whom she did not know, as if to say, “You are all right, if she
recommends you.”
“Ask her if she has any relatives here or in her own country,” said Mr.
Bonstone to Ellen.
Ellen, making use of a lingo I did not understand, put the question
to her.
The woman made vehement gestures, “No, no, the baby is free.”
“Her father was well off,” said old Ellen in a low voice. “He had cattle
and sheep, but he was cruel. He beat her, when she said she would
not marry a rich, old man. She hated them both, and ran away with
a poor young man who helped with her father’s flocks. Then he
died.”
“Did she tell you this?” asked Mr. Bonstone.
“No, sir, the other Syrians. She asked them to take her baby after
she died, not to let the old grandfather know. He likely would not
have it, anyway.”
“But these people are poor,” said Mr. Bonstone, “and that room
seems half full of children.”
“They are very good to each other,” said Ellen simply, “but they
would be very glad to get rid of it. She wants you to have it, too.
See her face.”
The poor young woman, brushing back her long, thick, black hair
from her clammy-looking forehead, motioned to the girl to give her
the baby.
She could not hold it properly, on account of the pain in her back.
Her groans were dreadful, but she steadied herself, and pulled a
cross out of the breast of her gown—the poor creature had no nice
white nightie like rich ladies. She was in bed with her street dress
on.
She wanted Mr. Bonstone to swear on the crucifix that he would be
good to her child.
The scene was pitiful, and Mr. Bonstone, strong man as he was,
almost broke down. Tears rolled down his cheeks, and he bit his lip
painfully. He took the cross in his hands—he promised solemnly to
provide for the child, and if he could not keep it himself, to find a
good home for it.
The poor creature could not understand a word he said, but she
knew just as well what he was saying, as if she had been born in
America. Her child was safe, and something told me that her
mother-soul was deeply gratified that a person evidently rich and of
good position would stand between the cold world and her little,
helpless, brown baby.
She took the baby on one arm, and began to kiss and caress it for
the last time, for Ellen had told her that the gentleman wished to
take it away. Her moans of pain, and her broken exclamations of
mother-love were too heart-rending. I could not stand it, and ran out
into the hall.
Mr. Bonstone came out presently with the baby in his arms. “This is
awful,” he said to Ellen. “Why did they not send her to the hospital?”
“You don’t understand these people, sir. They don’t know what
hospitals are. If they do, they are frightened of them. She begged to
stay with her child. She has had good attention, sir. You see she
wasn’t brought up like you.”
Mr. Bonstone’s lip drooped. Ellen didn’t know what an adventurous,
strange career he had had.
How carefully he went down the steps with the baby, after he had
thanked Ellen for her interest, and had slipped something into her
hand. He held it quite nicely to him all the way home. I think he
liked it.
Mrs. Bonstone must have been listening for the taxi, for she met us
in the doorway.
She never said a word, just held out her arms. Her husband put the
baby in them, and she ran to the smoking-room.
There she was, unwrapping it when Mr. Bonstone came in.
“Oh, Norman, Norman, Norman,” she said over and over again,
“what a dear little brown baby!”
She kissed it, and squeezed it, and asked how old it was, and where
he had got it.
He said it was a year old.
“Ah!” she said profoundly, “then I am twelve months ahead of
Clossie. Isn’t it a darling,” she went on, “such liquid eyes, and such
lovely hair, and it isn’t a bit frightened.”
“It’s been used to living in a crowd,” he said dryly.
“But its clothes,” she said, “they’re old, and faded, and just a little
smelly. Norman, we shall dress her like a princess—what’s her
name?”
Alas! he had forgotten to inquire.
“Never mind, dear,” she said consolingly. “It doesn’t matter. I’d like
to name her myself. You say she’s Syrian. She shall be Cyria, spelt
with a ‘C’ instead of an ‘S’—C-y-r-i-a—isn’t that pretty?”
He acknowledged that it was.
“Now, tell me all about the mother,” she said, “but first drag that
little rocking-chair near the fire, so I can rock her.”
It was hard for Mr. Bonstone to describe the intensely painful scene
with the mother, but he did so manfully.
“Norman,” she screamed, “you didn’t take this baby from a dying
woman!”
“You said you wanted it to-night,” he replied bluntly.
“Isn’t that like a man,” she said tragically. “Take it back,” and she
held it out to him.
“You don’t understand,” he replied. “I offered to leave it. The mother
kissed your face in the photograph, and refused to have me keep
the baby from you. I think she was afraid something might happen
after she died to prevent your getting it.”
“I shall go right to her,” said Mrs. Bonstone. “Call another taxi.”
The dear, patient man got another taxi, and with him, Mrs. Bonstone
flew off to the mother. I did not go this time, but I heard her telling
my master the next morning all about it.
It seems the Syrian mother was frightfully ill when they got there.
Mrs. Bonstone stayed with her, and sent her husband to get a nurse
for the mother, and one for the baby. He spent a part of the night in
this agreeable pursuit, and by breakfast time the Bonstones, nurse
and baby were comfortably settled on Riverside Drive.
Money does certainly oil the wheels of life. How long it would have
taken a person on foot to accomplish what the Bonstones did that
night! I could not help thinking of some further lines the English
greyhound taught me—
“As I sat in my café, I said to myself,
They may talk as they please about what they call pelf.
But help it, I can not, I can not help thinking,
How pleasant it is to have money, heigh ho!
How pleasant it is to have money!”

A little while before lunch, Mrs. Bonstone called us dogs to go to the


nursery with her. It was a room that had been quickly fitted up for
the brown baby. What a transformation in the little creature! Some
one had been up bright and early, shopping for Miss Cyria. She
looked a little aristocrat in lace and muslin, and how deliciously she
smelt—just like a faint lily of the valley. What an up-bringing that
child would have!
Mrs. Bonstone, or that good little Wasp, as Gringo called her now,
paid two long visits every day to the baby’s mother as long as the
poor thing lived.
Sometimes Mr. Bonstone went with her. As I have said before, the
man was no talker, but I heard him one day in the smoking-room,
which both men haunted, though neither smoked. (I have forgotten
to say that we had been invited to spend a week at the Bonstones,
and the two men got to be great friends.) Well, this day Mr.
Bonstone was telling my master of the Syrian woman’s actions when
her beautiful child was brought in to her tiny room that first night.
“I never saw anything like it,” he said, “that poor wretch racked by
pain. She draws herself up—stares at that old Ellen, at the child—at
my wife’s picture—then she gets out that cross. ’Pon my word I
nearly broke down—she’s a living martyr, but the awful joy of her
face. I say, Granton—there’s something about mothers, men can’t
comprehend.”
“There’s nothing like it,” my master said softly, then he went on to
tell about his wife and his baby.
“Queer, isn’t it, more of the well-to-do don’t adopt these
youngsters,” said Mr. Bonstone. “Cyria is going to be a beauty.”
“You’ll bring her up as your own child, I suppose,” said master.
“I guess so—after that mother.”
“You’re not afraid of heredity?” said master.
“Fudge, no—it’s up to us to shape her.”
“Frightens one, doesn’t it,” said master.
Mr. Bonstone smiled one of his rare, peculiar smiles.
“Yes, and leads you on, too, like a beacon. If Stanna and I have no
children, that child may be the light of our old age.”
At that moment, she came in the room with the brown baby in her
arms.
“I just wanted you to see her this morning, Norman,” she said, “she’s
so unusually sweet.”
Her adopted father chuckled to her, and clucked quite like a real one.
Master examined her with the eye of a connoisseur, then as he could
never help dragging in his own young one, he said, “She seems like
a giantess compared to my small son.”
“Just look at her dimples, Norman,” continued Mrs. Bonstone. “Aren’t
they fetching this morning, and that cute little way her hair curls
round her forehead? Seems to me, it’s more curly than usual.”
“And her lovely dark skin,” said Mr. Bonstone grimly. “Say, Stanna—
you’re not planning any nonsense about keeping the knowledge of
her people from her?”
“Do you suppose I would ever allow a child of mine to be ashamed
of its origin?” said Mrs. Bonstone. “I have taken her several times to
see those good creatures who were willing to adopt her. They are
not a bit envious, and finger her pretty clothes with the utmost
satisfaction. It reminds me of the first day her poor mother saw her
dressed up. Oh! Norman, if you could have seen her face. Cyria did
look like an angel in her white silk cloak and bonnet.”
“That’s fine,” said her husband, then he nudged master to listen to
the song his wife had begun to sing.
She had dropped into her little rocker that she kept in the smoking-
room among the men’s big chairs, and she was going over
something of her own composition in a low voice, holding the baby’s
face against her own as she sang—

“I never had a baby, but I know a little song,


And I sing it to my baby that does to me belong,
She’s the sweetest little baby that ever I did see,
The brownest, sweetest baby and she’s all the world to me!”

Now, I didn’t think this was so very clever, and I don’t think master
did, but Mr. Bonstone was so enraptured that he paid a young man a
handsome sum to round out this song about the brown baby and set
it to music, and strange to say, the simple words and the air became
so popular that I even heard boys whistling it in the streets of New
York.
After a time, the poor mother died, and was buried at Mr. Bonstone’s
expense.
“My! my! what a funeral they gave her,” said old Ellen. “If ever the
Bonstones want anything from the Syrians on this avenue, all
they’ve got to do is to say it.”
I was greatly excited about our own baby, and oh! how I longed to
see it, but my turn did not come for several weeks.
Master used to motor out every afternoon to see how mother and
child were getting on, but I was always left in the car, till one day,
when I squealed wildly for permission to go in, master took me into
the big hospital, and a nurse wiped me all over with a damp cloth
which had something on it that smelled queer. I think she was afraid
of germs.
When I was ushered into the sunny, lovely room where sat my
mistress, I felt all broken up. She was as thin as a scarecrow, and
just about as good-looking.
“See, Rudolph,” cried the poor thing, “even the dog scarcely knows
me.”
After that, there was nothing to do but to run up to her, wag my tail,
twist my body, and pretend that I was charmed to see her. Perhaps I
should not say pretend. I really, by this time, had gotten to be so
sorry for my poor mistress, that I pitied her—and when a dog pities
any one, it is only a step to love. Then I was sincerely and truly
delighted about the baby, because it had made my master happy,
quite happy. Of course, I should be jealous of it, but truly, when
master held it down for me to look at it, and I saw how gentle, and
harmless and helpless it was, with nothing but those two balled-up
fists to defend itself against the big, powerful world, something
swelled up inside me, and I vowed a good dog vow, that if any other
dog started to molest that little lump of flesh, I’d tear him limb from
limb.
I licked its little dress, and the nurse ran to get a dish with some
solution in it to wash the place I’d touched. Really, these nurses and
doctors carry things too far with their germ theories. Why wasn’t
master just as likely to have germs as I. We had both come through
the same parts of the city. Besides, I’m as clean as a whistle. Every
day Louis brushes me, and cleans my ears, and occasionally I have a
bath. Not too often, for it is not natural for dogs to be kept in soak.
Well—to come back to the day of my first visit to the baby. Master
was so pleased to think I liked the baby, that I got an extra share of
petting on the way home.
We were alone in the car, and I was sitting close up beside him. As
we were passing through Mount Vernon I began to think of the Lady
Gay cat. That cat had been on my mind for a long time, and one
evening I had scampered down to her eating-house on Sixth Avenue
to see how she was getting along.
She was not there. She had left some time ago, another cat told me,
after I had persuaded him to stand long enough for me to question
him. I wondered what had become of her. Had she found her way
back to this pretty place to her own good mistress, or was she dead
or perhaps stolen again?
THE LADY GAY CAT
CHAPTER XIII
THE LADY GAY CAT

J ust here something extraordinary happened, and I must say in


connection with it, that I have marvellous luck in remeeting
persons and animals.
My master suddenly exclaimed, “I am frightfully thirsty, Boy. Let us
stop at this nice little cottage, and see if that old lady in the window
will give me a drink.”
Master drew up the car by the side of the road, got out, and I
jumped after him, and whom do you think I saw rolling on a bed of
cat-nip under the kitchen window—my acquaintance of a night some
time ago—the Lady Gay cat.
She knew me at once, and with a surprised purr sprang toward me.
“How do you do, dog, I am glad to see you. I believe you saved my
life by getting me to stop stuffing myself. It was my only pleasure in
that dreadful place, and it cost some effort to give it up.”
“Do tell me about yourself,” I begged her, “and hurry up. Master
won’t wait long, I’m sure.”
She smiled the smile of superior knowledge. “Yes, he will, when
Granny gets talking to him. She’s the most crackajack old woman
you ever saw.”
“Her face looked fine,” I said, “as I saw it through the window.”
“Ah! she’s the woman for me,” said the cat fervently, “but you want
to know how I got back to her. Just after that evening I saw you,
things began to go badly at the eating-place. The help broke the
dishes, and got saucy, the people off the street didn’t patronise us,
the man broke his leg, and the woman got melancholy. One day
when she sat staring at the floor, I happened to pass in front of her.
“‘I believe it’s that black cat,’ she said, springing up and running to
the room where her husband lay in bed. ‘We’ve had bad luck ever
since we picked her up.’
“‘Don’t be a fool,’ he said roughly.
“But he couldn’t stop her. ‘It’s true,’ she said, ‘I’ve heard bad luck
always follows stolen animals, and your luck don’t change till you
take ’em back.’
“The man was quite angry, but he couldn’t change her. Didn’t she,
the next Sunday, in spite of their lack of money, take the train and
bring me out here.
“She brought the basket in which she had confined me right in here
to Granny. ‘Look here,’ she said (she is a great, fat woman and very
outspoken), ‘I did an awful thing a few weeks ago. I stole the cat I
saw sitting near this house. I don’t know whether it’s yours or not,
but I want you to help me get it back to its rightful owner. I believe
it brought a kind of spell on me.’
“Granny opened the basket, and oh! how gently she took me out
and stroked my fur. ‘It’s my cat,’ she said, ‘and I thank you for
bringing her back. Sit down, and I’ll make you a cup of tea.’
“The woman was very glad to sit down, and have some tea and talk,
after her ride in the train, and while I licked my fur into shape, I
listened to what my dear old Granny said to her. Now, I want to tell
you this, just to convince you what a good mistress I had, for you
seemed to think I was a little soft to mourn so much.
“Said Granny, ‘Why did you steal my cat?’
“‘To hunt mice,’ said the woman. ‘An eating-house always draws
them.’
“‘But, you could have got one in the city. Why take my little friend,
who loves the country?’
“‘City cats ain’t no good,’ said the woman. ‘They’re all sick, except
the rich cats that have a nice place to play.’
“‘Stealing is always wrong,’ said Granny.
“‘You bet it is,’ said the woman. ‘I ain’t goin’ to steal nothin’ again. I
was brought up right. I had a good mother.’
“‘How is your business getting on?’ then asked Granny, for she likes
to know all about any one she sees.
“‘Rank,’ said the woman, ‘the place needs a new fit-out, and the
landlord won’t do it.’
“‘By fit-out, what do you mean?’ asked Granny.
“‘I mean new paper, new linoleum, some mirrors—folks love to stare
at themselves, and I want a little closet fitted up with a looking-glass
and a wash basin, so the shop-girls can fix their hair, and powder
their faces when they comes in to eat.’
“‘How much would it cost?’ asked Granny.
“‘Two hundred dollars at the least,’ said the woman in a dreary way.
‘It’s a big place.’
“Granny went to her grandmother’s soup-tureen in the closet, and
took out her stocking. She has a stocking, you know, but you must
not tell any one. She doesn’t believe much in banks.”
“She wasn’t going to give the woman money, was she?” I inquired.
“Wait and see,” said the cat, who spoke quite slowly and mouthed
her words, as if she did not often have a listener.
I find that longing to talk with cats and dogs and human beings too.
So many are ready to talk—so few want to listen.
Well, the black cat went on to tell me that the woman looked as
amazed as if she had seen a ghost, when good old Granny began
counting out the five dollar bills.
“‘You don’t mean to say you’re going to lend me the money,’ she
exclaimed.
“‘Just what I’m going to do,’ said Granny. ‘I’ve two good sons. I
brought ’em up right, and they slip me in a five-dollar bill every time
they write. I’m going to lend you what I’ve got.’
“‘You’re going to lend me money,’ cried the woman, ‘when I stole
your cat?’
“‘You’re going to be a better woman in the future, than you have
been in the past,’ said Granny. ‘I can see it in your eye.’
“Then the woman broke down and cried, but recovered herself when
Granny began to count the money. They went over it together, and
made out one hundred and ninety-five dollars.
“‘Take it,’ said Granny, holding out the stocking, ‘and bring it back
when you get good and ready. There’s no hurry.’
“The woman held tight on the stocking, but she said quite anxiously,
‘How much interest will you charge?’
“‘No interest,’ said Granny.
“This broke the fat woman all up. She cried and sobbed, and when
she found in addition that Granny didn’t want even an I. O. U., she
hugged and kissed her, as if she had been her daughter. She told
Granny all that had ever happened to her, and they became great
friends on the spot.”
“Hurry up,” I said to the cat, “I see master drawing on his gloves.”
We had moved into the cute little hallway of the cottage, and I could
look in through the kitchen door and see master talking to the old
lady who had made him a cup of tea just as she had done for the fat
woman. I think he was telling her about the baby, for she had a
photograph album on the table between them, and had been
pointing out pictures of little children to him.
“That’s a fine story,” I said—“what’s the end?”
“There isn’t any end,” said the black cat triumphantly. “It’s still going
on. The woman comes out here every Sunday evening when trade is
low, and she brings goodies to Granny, and Granny goes in to see
her once a week, and goes to a show with her, and tells me all about
it when she comes home.”
“And the restaurant,” I said, “did they make it over?”
“Granny says it’s a dream now, with bright yellow and red and purple
flowers on the wall, and a fine mirror, and lots of water and towels,
and there’s a big crowd all the time.”
“And the money?” I went on.
“Granny’s getting it all back—ten dollars a week, and the woman
loves her like a daughter. Granny never had a girl, just boys.”
I pushed my inquiries a little further, “And how does the woman
treat you?”
“Like a Christian. She says, ‘No one need ever say nothin’ agin’ black
cats to me. There’s more in animals than most folks reckon.’”
“Good-bye,” I said running after my master who had shaken hands
with the old woman, and was jumping into the machine. “That’s a
fine story. I’m mighty glad you had a safe exit from your troubles.”
“Call again,” said the cat to me, and “Call again,” called Granny to
master, as we sped away.
The next interesting thing that happened to me was the home-
coming of the baby. My! my! what a fuss—the apartment
refurnished, renovated, fumigated, aired and reaired. Master,
whistling as cheerfully as a school-boy, gave up his lovely front room
and bath to his little pickaninny.
“You and I won’t mind the view of the backs of apartment-houses,
will we, Boy?” he said to me.
Of course I didn’t mind. Anything to make him happy, and to keep
with him. I was mortally afraid he would get like those silly nurses,
and send me out of the house.
At last, the great day came, and master and I took the car out to the
hospital. Mistress all wrapped up and veiled, and baby and nurse got
into it, and we tooted back to the city.
Master had warned the maids that mistress had got very thin and
nervous, and they must be extra gentle and quiet in their manner
with her. They were lovely to her face, but they almost cried in the
kitchen over her changed looks.
“Oh! dear,” whimpered cook, “ain’t she the holy fright—the darlin’
thing,” and Annie said something even worse. However, from that
day on, they never criticised her as sharply as they had before. The
baby had brought a new spirit into the house.
My dear master still thought his wife was beautiful, and I could see
that he was perfectly terrified, lest she should eat too many sweets
and get fat again. He offered her a diamond necklace, if she would
stop eating chocolates, and he watched her at the table, and coaxed
her not to touch any puddings that had a rich sauce.
One day, he found a little bit of brown paste on her upper lip.
“Dearest,” he said anxiously, “have you been eating chocolates?”
She blushed like a naughty child. “Just one,” she said; “nurse had
some. But I won’t do it again,” she went on shaking her head, “I’m
really anxious to please you, Rudolph.”
He kissed her quite warmly for him, and pushing the table away, sat
down quite close beside her, and began to read.
I was delighted that she liked to have him read to her now, but it
made a great difference to me. She used to watch the clock with
cunning eyes, and get more and more interested in what he was
reading, the later the evening grew. Sometimes, she asked a
question which did not exactly fit in, for example when he was
declaiming about the war in Poland, and she said, “I always did
dislike Spaniards.”
He laid down his book. “I said nothing about Spaniards, my dear.”
Her thoughts had been wandering, and she couldn’t speak till he
gave her a clue. “I was reading of the woes of the Poles.”
“That is what I meant,” she said, “Poles of course, I never did care
for them.”
“I didn’t know you had ever met any,” he said dreamily, then he
plunged again into his book.
She was nearly dead with sleep that night, and soon she said,
“Rudolph, would you just read me something about children, before
I go to bed?”
He put down the war-book, and took up one of poetry. I was sleepy
too, but I caught a phrase, “The cry of the children,” and later in the
night, this phrase came back to me.
We had no walk—it was too late to go when mistress went to the
baby, and master said to me, “Let us turn in too, Boy-Dog.”
It was good we got a little sleep early in the night, for we had rather
a disturbed time later.
While master was undressing, he talked to me about children. “Poor
little wretches,” he said. “How much they have to cry about. So
many troubles that they outgrow with age.”
I listened to him with interest. I used not to know much about
children, for I had never been thrown much with them, my owners
being mostly childless or unmarried persons. However, as I told
Gringo when I first met him, I had a great respect for the very
young of the human kind, and I thought them remarkably clever.
Since the baby came, I had been observing him closely. His little
face looked to me very wise, and sometimes his expression was
almost painful, as if he were trying to tell us something of a
wonderful place he had come from. But the poor little soul had no
words to express his thoughts. He just waved his little fists, and
rolled his head in despair.
Master had gone quite daffy on the subject of babies. Dating from
the day that he had heard of the arrival of the baby, he stared at
every child he met in the street. He gave pennies to poor children,
and watched them with delight when they ran to a candy shop. He
stopped the perambulators of rich babies, and begged permission of
the nurses to look at them. All babies were dear to him, because he
had one of his own.
To come back to this night, I slept for a while, then I woke up with a
feeling of great distress. Some one was in trouble near me. I could
hear nothing, smell nothing, but I knew it was so, and I sprang
uneasily from the big chair where I slept, and went to my master’s
bed.
CHAPTER XIV
HIS MOTHER’S BOY

H e was sleeping like a boy. I hated to disturb him, and I ran to


the door leading to the hall, and smelt hard under it. Nothing
there—I went back to bed, but my uneasiness increased so terribly,
that, at last, if I had not aroused my master, I should have burst into
terrible howling which would have disturbed the household and
waked the baby.
I pulled hard at the sleeve of his pajamas. “Master, master, wake
up.”
He turned on me eyes unseeing at first, then intelligent. “What’s the
matter, Boy-Dog—burglars?”
I didn’t know what was the matter, so I pulled hard to show he was
to come and investigate.
He rolled quickly out of bed, snatched his bath-robe and followed
me. He knew that I would not rouse him for a trifle.
We stole out into the hall like two cats. There I was puzzled. Which
way did the uneasiness lead me? Master, of course, went right
toward the door of the precious baby’s room, but I turned my back
on it, and led him to the door leading out of the apartment into the
general hall.
Master, with a greatly relieved face, softly unlocked it, and we stood
together outside. There were several other apartments on this floor
—the trouble was in one of them.
Ah! at last I caught it, the faint sound of sobbing. I rushed to the
door of a pretty delicate little English woman whose husband had
gone to the war. I laid my ear to the crack underneath—yes, it was
there, the sound of a child crying in the night.
I scratched, and whined, and looked up at master. He listened and
heard nothing, but he had such confidence in my judgment, that he
pressed the electric button.
No reply, and the sobbing stopped suddenly. The trouble was still
there, however, and I redoubled my scratching at the door.
Master rang again, then tried the door softly.
Finally he called in a low voice, “Mrs. Waverlee!”
She did not reply, then he said, “Egbert, Egbert, are you awake? It is
Mr. Granton.”
There was a dead silence. I thought it was pretty good in master to
stand there so patiently. He could hear nothing, see nothing, but he
relied on me.
Suddenly there was a noise inside, like a chair falling over. A little
voice cried, “Oh!” then a trembling hand began to fuss with the lock
of the door, and at last it was thrown silently open.
We stepped inside. Confronting us was young Egbert Waverlee in his
little nightie, his face swollen and disfigured from much weeping. He
was trembling with the cold, for all the windows were open.
He held out his little hand. “Mr. Granton, I can’t wake muvver,” he
said with quivering lip, “and she’s getting cold.”
He was a dear little lad, and often came to call with his mother on
my mistress, but lately we had not seen much of them. I knew that
her husband had gone to England, and she was feeling very sad
about it.
My master strode quickly past the child to his mother’s room. She
was not in bed, she lay all in a heap on the floor, beneath a large
picture of her husband.
As my master lifted her in his strong arms, and laid her on her bed,
a pencil fell from her cold fingers to the floor. He saw it, also a piece
of notepaper with a crest on it, and presently he picked them both
up and put them in his pocket.

You might also like