100% found this document useful (7 votes)
89 views

Get Fundamentals of Python: Data Structures 2nd Edition Kenneth A. Lambert Free All Chapters

Kenneth

Uploaded by

munirathey
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 (7 votes)
89 views

Get Fundamentals of Python: Data Structures 2nd Edition Kenneth A. Lambert Free All Chapters

Kenneth

Uploaded by

munirathey
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/ 52

Download the full version of the textbook now at textbookfull.

com

Fundamentals Of Python: Data Structures 2nd


Edition Kenneth A. Lambert

https://textbookfull.com/product/fundamentals-of-
python-data-structures-2nd-edition-kenneth-a-
lambert/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Fundamentals of Python: First Programs, 2nd Edition


Kenneth A. Lambert

https://textbookfull.com/product/fundamentals-of-python-first-
programs-2nd-edition-kenneth-a-lambert/

textbookfull.com

Data Structures & Algorithms in Python John Canning

https://textbookfull.com/product/data-structures-algorithms-in-python-
john-canning/

textbookfull.com

Data Science Fundamentals for Python and MongoDB 1st


Edition David Paper

https://textbookfull.com/product/data-science-fundamentals-for-python-
and-mongodb-1st-edition-david-paper/

textbookfull.com

Intuitive Fasting The Flexible Four Week Intermittent


Fasting Plan to Recharge Your Metabolism and Renew Your
Health 1st Edition Will Cole
https://textbookfull.com/product/intuitive-fasting-the-flexible-four-
week-intermittent-fasting-plan-to-recharge-your-metabolism-and-renew-
your-health-1st-edition-will-cole/
textbookfull.com
Making Space for the Dead: Catacombs, Cemeteries, and the
Reimagining of Paris, 1780–1830 1st Edition Erin-Marie
Legacey
https://textbookfull.com/product/making-space-for-the-dead-catacombs-
cemeteries-and-the-reimagining-of-paris-1780-1830-1st-edition-erin-
marie-legacey/
textbookfull.com

Encounters with Popular Pasts Cultural Heritage and


Popular Culture 1st Edition Mike Robinson

https://textbookfull.com/product/encounters-with-popular-pasts-
cultural-heritage-and-popular-culture-1st-edition-mike-robinson/

textbookfull.com

System Reliability Management: Solutions and Technologies


1st Edition Adarsh Anand (Editor)

https://textbookfull.com/product/system-reliability-management-
solutions-and-technologies-1st-edition-adarsh-anand-editor/

textbookfull.com

The Epilepsy Prescriber s Guide to Antiepileptic Drugs 3rd


Edition Philip N. Patsalos

https://textbookfull.com/product/the-epilepsy-prescriber-s-guide-to-
antiepileptic-drugs-3rd-edition-philip-n-patsalos/

textbookfull.com

Creating Web Animations Bringing Your UIs to Life 1st


Edition Kirupa Chinnathambi

https://textbookfull.com/product/creating-web-animations-bringing-
your-uis-to-life-1st-edition-kirupa-chinnathambi/

textbookfull.com
Research and Practice in Infant and Early Childhood Mental
Health 1st Edition Cory Shulman (Auth.)

https://textbookfull.com/product/research-and-practice-in-infant-and-
early-childhood-mental-health-1st-edition-cory-shulman-auth/

textbookfull.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.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
 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.
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
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.
Random documents with unrelated
content Scribd suggests to you:
The Project Gutenberg eBook of Mikaeli Kohlhas
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.

Title: Mikaeli Kohlhas


Saksalainen tapakomedia Lutheruksen ajoilta

Author: Heinrich von Kleist

Release date: April 10, 2024 [eBook #73372]

Language: Finnish

Original publication: Jyväskylä: Jyväskylän kirjapaino, 1884

Credits: Tapio Riikonen

*** START OF THE PROJECT GUTENBERG EBOOK MIKAELI


KOHLHAS ***
MIKAELI KOHLHAS

Saksalainen tapakuvaelma Lutheruksen ajoilta

Kirj.

HEINRICH VON KLEIST

Suomennos

Jyväskylässä, Jyväskylän kirjapaino, 1884.

Mikaeli Kohlhas.

Haweljoen rannoilla Saksan maakunnasta Brandenburg'issa eli


kuudennentoista vuosisadan keskivaiheilla muuan hevoskauppias,
nimeltä Mikaeli Kohlhas, erään koulunopettajan poika, sekä samalla
kertaa aikansa hurskasmielisimpiä ja hirveimpiä ihmisiä. Tätä
verratonta miestä olisi hänen kolmanteenkymmenenteen
ikävuoteensa saakka voinut pitää hyvän kansalaisen esikuvana.
Eräässä kylässä, jolla vieläkin on hänen nimensä, oli hänellä talo,
jossa hän rauhallisesti eli ammatistaan, hevosten kasvattamisesta ja
myymisestä. Lapset, jotta vaimonsa hänelle lahjoitti, kasvatti hän
Jumalan pelvossa ahkeruuteen ja rehellisyyteen; ei ollut ketään
hänen naapureistansa, jota ei hänen hyväntekeväisyytensä ja
oikeudentuntonsa olisi hyödyttänyt, sanalla sanoen: kaikki, jotka
olivat olleet jossakin yhteydessä hänen kanssansa, olisivat
siunanneet hänen muistoansa, ellei eräs seikka olisi saattanut häntä
harhateille; hänen väkevä tunteensa siitä, mikä on oikeata,
yhteydessä itsepäisyyden kanssa, joka jo meni uppiniskaisuuteen
saakka, teki, näet, hänestä sekä kapinoitsijan että murhamiehen.

Kerran kuljetti hän ratsahin muutamia nuoria hevosia, jotka kaikki


olivat hyvin ruokitut ja kiiltokarvaiset, ja jotka hän aikoi viedä
ulkomaille. [Jo ennen tätä aikaa oli Saksan valtakunta melkein
kokonaan hajoutunut monenlaisiin pienempiin ja suurempiin
valtioihin, jotka olivat niin itsenäisiä, että niitä hyvin kyllä voi sanoa
"ulkomaiksi" toistensa suhteen. Todisteena valtioitten yhteydestä oli
pääasiallisesti ainoastaan yhteinen keisari, joka silloin asui Wien'issä
ja tuomioistuin, joka oli perustettu tuomitsemaan rikoksia
maanrauhaa vastaan.] Hän teki juuri laskuja, mitenkä hän käyttäisi
sen voiton, jonka hän toivoi näistä markkinoista saavansa — osittain,
kuten hyvät talouden hoitajat tavallisesti, saadaksensa sillä uutta
voittoa, osittain hyödyksi ja huviksi heti paikalla — kun hän saapui
Elbejoelle ja saksilaisella alueella muhkean ritarilinnan edustalla
huomasi puomin, jota hän ei ennen tällä tiellä ollut nähnyt. Hän pysyi
alallaan hevosineen hetkisen, vaikka juuri ankarasti myrskysi ja
satoi, sekä huusi puomin vartiata, joka heti kurkistikin akkunasta,
jörömäisenä kasvoiltansa. Hevoiskauppias pyysi, että puomi
nostettaisiin.
— Mitä uusia laitoksia nämät ovat? kysyi hän, kun vartia hyvän
ajan kuluttua tuli huoneesta ulos.

— Maaherran myöntämä etuoikeus junkkeri Wenzel von Tronkalle,


vastasi tämä, aukaisten samassa puomin.

— Vai niin! sanoi Kohlhas. Onko junkkerin nimi Wenzel? ja hän


tarkasteli linnaa, joka loistavine salkoineen kohosi korkealle yli
seudun. — Onko vanha herra kuollut?

— Hän kuoli halvauksesta, vastasi vartia: nostaen samassa


puomin ylös.

— Hm, sepä oli vahinko, jatkoi Kohlhas; hän oli kunnioitusta


ansaitseva vanha herra, joka iloitsi siitä, että ihmiset kulkivat; hän
edisti kauppaa ja liikettä, missä vaan voi, ja teetti kerran
kivilaskoksen sen vuoksi, että eräs minun tammoistani loukkasi
jalkansa siinä, missä tie menee kylään. No, mitä minun sitten tulee
maksaa? kysyi hän, ottaen vastenmielisesti tuulessa liehuvan
viittansa alta rahat, joita vartia häneltä vaati. — Kyllä, kyllä, vanhus!
lisäsi hän kun vartia sopisi: kiireesti, kiireesti! Kohlhas valitti pahaa
säätä ja lausui, että heille kummallekin olisi ollut parempi, jos tuo
salpapuu olisi saanut jäädä metsään kasvamaan. Samassa antoi
hän vartialle rahat ja aikoi ratsastaa eteenpäin, mutta oli tuskin
ehtinyt salpapuun alle, kun hän kuuli toisen äänen tornista huutavan:
Seis siellä, sinä hevoshuijari! samassa näki hän linnanvoudin
sulkevan akkunan ja kiirehtivän hänen luoksensa tielle.

— No mikähän nyt taas mahtaa olla asiana? kysyi Kohlhas


itseltänsä ja pysähtyi hevosineen. Linnanvouti tuli, napiten vielä
yhden päällysnutun suuren vatsansa suojaksi, ja kysyi, kääntyen
selin tuuleen päin, olisiko Kohlhasilla passia?
— Passia? sanoi Kohlhas jotenkin hämmästyksissään.

Linnanvouti katseli häntä syrjästä ja sanoi, että ilman maaherran


luvatta ei kukaan hevoskauppias saanut hevosineen mennä rajan
ylitse.

Hevoskauppias vakuutti, että hän oli kokonaista seitsemäntoista


kertaa kulkenut rajan ylitse ilman tuollaista lupakirjaa ja että hän
tarkoin tunsi hänen ammattiansa koskevat määräykset; tämä mahtoi
olla jokin erehdys, ja hän pyysi senvuoksi voudin asiaa ajattelemaan
ja ettei häntä hänen vahingoksensa viivytettäisi, sillä hänellä oli pitkä
päivän matka.

Vouti vastasi, ettei hän enään kahdeksattatoista kertaa pääsisi


rajan ylitse. Säädös oli hiljakkoin julaistu ja Kohlhas'in täytyisi joko
lunastaa passi tahi palata jälleen sinne, mistä oli tullutkin.
Hevoskauppias, jota jo alkoi suututtaa nämät laittomat kiskomiset,
astui vähän mietittyänsä alas hevosensa selästä, jätti sen
palvelijansa huostaan ja sanoi aikovansa itse puhua asiasta junkkeri
von Tronkan kanssa. Hän astui ylös linnaan voudin seuraamana,
joka höpisi jotakin likaisista rahankiskojista ja miten hyödyllistä olisi
niitä nytistää, ja molemmat astuivat saliin toinen toistansa äkäisesti
silmäillen. Sattui juuri niin, että junkkeri istui pikarin ääressä
muutamain iloisten ystäväin parissa hauskojen pilapuheiden
aikaansaaman hillitsemättömän naurun kaikuessa, kun Kohlhas
lähestyi häntä valitustansa esittääksensä. Junkkeri kysyi, mitä hän
tahtoi, ja ritarit vaikenivat nähdessään vieraan miehen. Mutta tuskin
oli Kohlhas ehtinyt hevosiansa koskevaa pyyntöä esittääkään,
ennenkuin koko joukko, huutaen: hevosia! missä ne ovat? riensi
akkunaan saadaksensa niitä nähdä; ja huomattuansa tuon loistavan
parven, kiinihtivat he junkkerin ehdotuksesta alas pihalle. Sade oli
tau'onnut; linnanvouti, linnanhoitaja ja rengit kokoontuivat herrojen
ympärille, ja kaikki tarkastelivat eläimiä. Toinen kiitti piirtopäätä
rautiota, toinen kastanjan ruskeata, joku taputteli mustankeltais-
täplikästä kimoa, ja kaikkein mielestä hevoset olivat kuin hirviä, ja he
sanoivat, ettei parempia hevosia maassa ole kasvatettu.

Kohlhas vastasi iloisesti, että hevoset eivät olleet parempia kuin


ne ritaritkaan, jotka niillä tulisivat ratsastamaan, ja kehoitti heitä niitä
ostamaan. Junkkeri, joka mielistyi suuresti väkevään rautiaasen,
kysyi sen hintaa, ja linnanhoitaja kehoitti häntä ostamaan parin
mustia, nyt kun he juuri olivat työhevosten tarpeessa. Kun Kohlhas
oli hinnan ilmoittanut, katsoivat ritarit sen kuitenkin liian kalliiksi, ja
junkkeri sanoi, että hevoskauppiaan täytyisi ratsastaa ympyriäisen
pöydän ritarien luokse ja etsiä kuningas Arthur [tarkoittaa Keskiajalla
paljon luettua ritaritarinaa kuningas Arthurista ja ympyriäisen pöydän
ritareista] käsille, ennenkuin hän saisi niin korkean hinnan. Kohlhas,
nähtyänsä linnanvoudin ja hoitajan kuiskuttelevan keskenänsä ja
heittämän samassa selkeitä silmäyksiä hevosiin, teki himmeästä
aavistuksesta, mitä voi, saadaksensa luovutetuksi hevosensa.

Hän sanoi junkkerille: herra, minä olen ostanut hevoset kuusi


kuukautta sitten 25 guldenista; antakaat minulle 30, niin saatte
hevoset!

Kaksi ritareista, jotka seisoivat junkkerin vieressä, huomautti


kylläkin selvästi, että hevoset olivat sen arvoisia, mutta junkkeri
sanoi, että rautiaasta hän kyllä jotakin antaisi, mutta ei työhevosista,
ja oli juuri tiehensä menemäisillään, kun Kohlhas arveli, että he ehkä
tekisivät kaupan, kun hän toiste tulisi sinne hevoseen, sanoi
jäähyväiset ja tarttui hevosensa ohjaksiin eteenpäin
ratsastaaksensa.
Samassa astui linnanvouti joukosta esiin ja sanoi Kohlhas'in jo
kerta kuulleen, ettei passitta kenkään saanut matkustaa. Kohlhas
kääntyi junkkeriin ja kysyi olisiko asian laita todellakin niin, josta
hänen ammattinsa tulisi paljon haittaa kärsimään. .

Junkkeri vastasi, hämmästynein muodoin poistuessaan: Niin


Kohlhas, passi sinun on lunastettava. Puhu linnanvoudin kanssa ja
ratsasta sitten tiehesi.

Kohlhas vakuutti hänelle, ettei hän ensinkään tahtonut kiertää niitä


vaatimuksia, jotka hevosten maastaviennin suhteen olivat olemassa,
lupasi lunastaa passin mennessään Dresdenin kaupungin läpitse ja
pyysi päästä ainoastaan tämän kerran, hän kun ei ollut tiennyt tästä
velvollisuudesta mitään.

— No, sanoi junkkeri, kun vettä taas alkoi sataa ja myrsky vinkuen
puhalsi hänen tuimien jäsentensä läpitse, antaa sen veijarin mennä!
Tulkaa, sanoi hän ritareille, kääntyi pois ja aikoi nousta linnaan.

Mutta linnanvouti arveli, kääntyen junkkeriin, että Kohlhas'in


kuitenkin täytyisi jättää joku pantti vakuudeksi passin lunastuksesta.
Junkkeri seisahtui taas linnan portille. Kohlhas kysyi, minkälainen
pantti hänen olisi annettava, rahassako vai tavarassa? Linnanhoitaja
mutisi partaansa, että hän voisi jättää itse hevoset.

— Niin, mietti linnanvouti, sepä onkin parasta; kun passi on


lunastettu, voi hän noutaa hevoset milloin vaan haluaa.

Hämmästyneenä noin hävyttömästä vaatimuksesta, sanoi Kohlhas


junkkerille, joka seisoi viluissaan pitäen nuttunsa lievettä vatsansa
edessä, että hän juuri hevosiensa myymisen takia oli matkalla, mutta
kun samassa tuulen vihuri heitti joukon rakeita ja vesipisaroita
portista pihalle, huusi junkkeri, tehdäksensä lopun tästä jupakasta:

— Jollei hän tahdo jättää hevosiansa, niin ajakaat hänet takaisin


puomin ylitse! Sen sanottuaan poistui hän.

Kohlhas, hyvin älyten, että hänen tässä täytyi peräytyä ylivoiman


edestä, päätti täyttää vaatimuksen, koska asia ei muuten päinsä
käynyt, irroitti hevoiset ja vei ne erääsen talliin, jonka linnanvouti
hänelle osoitti. Hän jätti yhden rengeistään niitä hoitamaan, antoi
hänelle rahaa ruokaan ja rehuihin, kehoitti häntä pitämään hevosista
hyvän huolen, siksi kun hän palaisi takaisin, ja jatkoi, vieden
muassaan jälellä olevan hevosjoukon, matkaansa Saksiin £eipzig'in
kaupungin juuritte markkinoille kahdella päällä siitä, olisiko todellakin
tuollaista veroitusta säädetty Saksin maalle, vahingoksi vasta
vaurastuvalle hevoshoidolle.

Kohlhas päästyänsä Dresden'in kaupunkiin, missä hänellä oli talo


ynnä muutamia tallia eräässä esikaupungissa, hän kun sieltä
tavallisesti kävi kauppaa pienemmillä markkinoilla, meni hän
kanseliin; siellä sai hän neuvosherroilta, joista hän muutamia tunsi,
tietää, mitä hän itsekin heti oli arvellut, että tuo passijuttu olikin aivan
perätön. Kohlhas, joka pyynnöstä sai näiltä tyytymättömiltä
neuvosherroilta kirjallisen selityksen sen valheellisuudesta, ihmetteli
junkkerin häpeämättömyyttä, vaikk'ei hän oikein vielä arvannut, mitä
junkkerilla oli mielessä; ja kun se hevosjoukko, minkä hän oli
muassaan tuonut, oli muutaman viikon kuluttua myyty, palasi hän
mielihyvillään kaupasta Tronkenburg'iin, tuntematta muita katkeria
tunteita, kuin maailman yleisistä puutteista.

Linnanvouti, jolle hän näytti selityksen, ei siihen mitään sanonut; ja


Kohlhas'in kysymykseen, voisiko hän nyt saada hevosensa takaisin,
vastattiin, että hän saisi mennä ne itse noutamaan. Mutta jo
mennessään pihan poikki sai Kohlhas kiusaksensa tietää, että hänen
renkinsä oli lyöty pahanpäiväiseksi ja karkoitettu tiehensä muutamia
päiviä senjälkeen kun hän oli Tronkenburg'iin jätetty, kuten sanottiin,
sopimattoman käytöksensä vuoksi. Hän kysyi mieheltä, jolta hän
tämän tiedon sai, mitä renki oli tehnyt, ja kuka sillä välin oli hevosia
hoitanut, johon tämä vastasi, ettei hän sitä tiennyt; sitten meni hän
talliin, missä hevoset olivat, ja hänen sydämensä alkoi jo käydä
levottomaksi pelottavista aavistuksista. Mutta miten suuresti hän
hämmästyi, kun hän kahden kauniin ja hyvin hoidetun hevosensa
sijassa näki parin laihtuneita ja kuivia hevosluuskia, korkealla
luusolmut, joita näyttiin voitavan ripustaa likeisempään koukkuun,
harja ja karva takussa, ilman ruokkoa ja hoitoa; eläimellisen
kurjuuden todellisia kuvia!

Kohlhas, jolle hevoset heikosti hirnuivat, kysyi, hirveästi


suutuksissaan, mikä niihin oli tullut? Vieressä oleva mies vastasi,
ettei mikään onnettomuus ollut niitä kohdannut, ne olivat kyllä
saaneet hyvän ruo'an, mutta kun juuri oli ollut elonleikkuun aika ja oli
puute vetojuhdista, oli niitä hiukkasen käytetty ulkotöissä. Kohlhas
murisi tästä häpeällisestä ja ilkeästä väkivaltaisuudesta, mutta
tuntiessaan voimattomuutensa, vaikeni hän ja varustautui jo
hevosineen jättämään tämän ryöväriluolan, sillä muutahan ei ollut
tehtävänä; mutta samassa tulikin linnanvouti, joka oli kuullut
sanakiistan, ja kysyi mitä oli asiana?

— Mitäkö on asiana! vastasi Kohlhas; ken on antanut junkkeri von


Tronkalle ja hänen väellensä oikeuden käyttää minun hevosiani
peltotöihin? Onko tuo ihmisellistä? kysyi hän vielä, kun koetti
ratsuruoskalla kerran lyöden saada eloa noihin uuvutettuihin
eläimiin, jotka eivät siitä liikahtaneetkaan.
Linnanvouti katsoi hetken uhkaavasti Kohlhas'iin ja sanoi sitten:

— Mikä rötkäle! Ikäänkuin ei teidän tulisi kiittää jumalaa, että vielä


vähän on henkeä teidän eläimissänne? Kukapa niitä olisi täällä
hoitanut, kun teidän renkinne on pötkinyt tiehensä? Eikö sitäpaitsi
ollut kohtuullista, että hevoset peltotöistä ansaitsivat sen ravinnon,
mikä niille annettiin? Lopuksi lisäsi hän, ettei Kohlhas'in pitänyt
melua pitää, muuten hän kutsuisi koirat esiin, ja niiden avulla hän
kyllä saisi rauhaa kartanolla.

Kohlhas'in sydän sykki kiivaasti hänen nuttunsa alla, hän tunsi jo


halun heittää tuon möhömahaisen solvaajan ovesta ulos, mutta
hänen oikeuden tuntonsa, joka oli kultakappaleen tapainen, horjui
vielä; hän ei vielä ollut sydämensä tuomioistuimen edessä varma
siitä, että hänen vastustajansa tässä oli syyllinen; vihaansa
tukehuttaen meni hän hevosten luokse, joitten harjoja hän suoritteli,
samassa kun hän äänettä mietiskeli asian suhteita ja kysyi, ääntänsä
hilliten, mistä hairahduksesta renki oli linnasta karkoitettu?

Linnanvouti vastasi:

Senvuoksi, että se heittiö niskoitteli täällä kartanolla; senvuoksi,


että hän kieltäytyi vaihtamasta tallia, vaikka se oli välttämätöntä, ja
vaati, että kahden junkkerin, jotka tulivat Tronkenburg'iin, olisi pitänyt
antaa hevostensa seisoa koko yön maantiellä hänen juhtiensa
tähden.

Kohlhas olisi mielellään antanut hevosten täyden hinnan, jos nyt


olisi saanut rengin käsille, voidaksensa verrata hänen lausuntonsa
linnanvoudin puheesen. Hän seisoi siinä vielä, suoritellen
hevostensa takkuuntuneita harjasuortuvia ja tuumien mitä tehtävänä
olisi asiain tällä kannalla ollessa, kun kaikki äkkiä muuttui siitä, että
junkkeri Wenzel von Tronka samassa tuli kotiin eräästä jänisajosta ja
ratsasti laukkaa linnan pihaan, perässään joukko ritaria, palvelijoita
ja koiria. Kun hän kysyi, mitä oli tapahtunut, otti linnanvouti heti
suunvuoron, ja koirien haukkuessa vieraan nähtyänsä, ja ritarien
koettaessa hillitä niitä, kertoi hän junkkerille, asiaa ilkeimmällä tavalla
vääristellen, mitä melua tämä hevoshuijari oli nostanut siitä, että
hänen hevosiansa oli hiukan käytetty, ja lisäsi, että Kohlhas ei
tahtonut tunnustaa hevosia omiksensa.

Kohlhas huudahti:

— Ne eivät ole minun hevosiani, herra; ne eivät ole niitä hevosia,


jotka olivat 30 guldenin arvoisia! Minä tahdon hyvin hoidetut, karskit
hevoseni takaisin.

Junkkeri astui hevosen selästä, jolloin pilaan haihtuva kalpeus


lensi hänen kasvoillensa, ja sanoi:

— Jollei tuo houkka tahdo ottaa hevosiansa takaisin, olkoon


ottamatta!
Tule, Günther! huusi hän lyöden tomua housuiltansa, tule, Hannu!
Viiniä! huusi hän sitten, kun oli ovella ritariensa seurassa, ja astui
huoneesen.

Kohlhas sanoi, että hän ennemmin hankkisi nylkyrin ja antaisi


nylkeä hevoset, kuin veisi ne talliinsa Kohlhasenbrück'iin,
semmoisina kuin ne nyt olivat. Huolimatta sen enempää niistä, jätti
hän ne siihen seisomaan, heittäytyi ruskonsa selkään, vakuuttaen
kylläkin ymmärtävänsä hankkia itsellensä oikeutta tässä asiassa, ja
ratsasti tiehensä.
Hän oli jo täydessä vauhdissa paluumatkalla Dresden'in
kaupunkiin, kun hän, ajatellessaan renkiänsä ja sitä valitusta, joka
linnassa oli tätä vastaan tehty, rupesi ratsastamaan käyden; ja
ennenkuin hän oli ehtinyt tuhannen jalkaa eteenpäin, kääntyikin hän
takaisin Kohlhasenbrück'iin, kuullaksensa ensin renkinsä selityksen
asiasta, johon häntä kehoitti sekä viisaus että varovaisuus. Sillä joku
lempeämpi tunne ja se, mitä hän jo oli kokenut maailman
vaillinaisuuksista, taivutti häntä myöntämään, että hän oikeudella oli
kadottanut hevosensa, jos vaan, kuten linnanvouti oli väitlänyt,
rengillä tässä oli jonninlaista syytä. Toinen tunne sitävastoin — ja
tämä juurtui häneen yhä syvemmälle, kuta edemmäksi hän matkusti,
sillä kaikkialla, mihin hän poikkesi, kuuli hän puhuttavan oikeuden
loukkauksista, joita Tronkenburg'issa joka päivä harjoitettiin
matkustavaisia vastaan — toinen ja yhtä jalo tunne sanoi hänelle,
että, jos kaikki tämä — ja siltä todella näyttikin — oli paljasta
kekseliäisyyttä, niin olisi hänen velvollisuutensa hankkia kaikin
voimin itsellensä kärsimien solvauksiensa hyvitystä ja
kansalaisillensa tulevaisuuden turvallisuutta.

Niin pian kuin hän oli päässyt kotiansa Kohlhasenbrück'iin, syleillyt


uskollista puolisoansa Lisbeth'iä ja suudellut lapsiansa, jotka
riemuitsivat hänen ympärillänsä, kysyi hän heiltä heti Herseä,
ensimäistä tallirenkiänsä, ja olivatko he mitään hänestä kuulleet.

— Kyllä, rakas Mikaeli, vastasi Lisbeth. Herse, ajattelepas! noin 14


päivää sitten tuli tuo miesparka julkeasti pieksettynä tänne, niin
lyötynä, että hän tuskin voi hengittääkään. Me asetimme hänet
vuoteelle, mihin hän jäi makaamaan verta sylkien, ja monen
kysymyksen perästä saimme kuulla kertomuksen, jota ei kukaan
voinut oikein ymmärtää: että sinä olisit jättänyt hänet Tronkenburg'iin
muutamien hevosten hoitajaksi, joita ei tahdottu laskea menemään,
ja että häntä olisi julmimmilla rääkkäyksillä pakoitettu linnasta
lähtemään, sekä että hänen oli ollut mahdoton saada hevosia
mukaansa.

— Vai niin, sanoi Kohlhas, ottaen viitan yltänsä; onko hän sitten jo
parantunut jälleen?

— Jotensakin, vastasi vaimo, mutta hän sylkee verta vielä. Minä


aijoin heti lähettää miehen Tronkenburg'iin hevosia hoitamaan, siksi
kun sinä tulisit; sillä kun Herse on aina näyttänyt puhuneen totta ja
olleen uskollinen meitä kohtaan, miten ei kukaan toinen, en minä
saattanut ollenkaan epäillä hänen sanojansa, joiden totuutta niin
moni seikka vahvisti, enkä uskoa, että hän olisi hevoset jollakin
muulla tavalla kadottanut; mutta hän pyysi sydämellisesti, etten minä
lähettäisi ketään tähän ryövärien luolaan, ja että mieluisemmin
luopuisin eläimistä, kuin uhraisin ihmisen niiden vuoksi.

— Vieläkö Herse makaa vuoteen omana? kysyi Kohlhas, riisuen


liinan kaulastaan.

— Hän on jo muutamia päiviä sitten alkanut käyskellä kartanolla.


Sinä saat kyllä nähdä, miten hänen laitansa on, ja että tämä tapaus
on yksi noista hävyttömyyksistä, joita matkustavia vastaan
harjoitetaan Tronkenburg'issa.

— Se on minun kuitenkin ensin selville saatava. Kutsu hänet


minun luokseni, jos hän on jalkeilla! Näin sanoen istui Kohlhas
nojatuoliin, ja hänen vaimonsa, joka hänen tyyneydestänsä oli
sangen iloissaan, meni miestä noutamaan.

— Mitenkä olet sinä käyttänyt itsesi Tronkenburg'issa? kysyi


Kohlhas, kun Herse Lisbethin kanssa astui huoneesen; en ole
sinuun juuri suuresti tyytyväinen.

Mies, jonka vaaleilla kasvoilla näkyi pari punaista pilkkua, oli


hetkisen äänettä ja sanoi sitten:

— Siinä teillä on oikeus, isäntä, sillä erään sytytyslangan


kappaleen, joka minulla sattumalta oli muassani, ja jolla aijoin pistää
tuleen tuon ryövärien pesän, josta minut karkoitettiin, heitin minä
Elbejokeen, kun kuulin lapsen huoneessa parkuvan ja tuumailin:
polttakoon linnan tuhaksi jumalan tuli, minä en sitä tahdo tehdä.

Hämmästyneenä sanoi Kohlhas:

— Mutta mitä sinä teit, että sinut ajettiin pois Tronkenburg'ista?

— Erään huonon kepposen vaan, isäntä, vastasi Herse pyyhkien


hikeä otsaltansa; mutta tehtyä tekoa emme voi peruuttaa. Minä en
tahtonut sallia, että hevosia peltotöissä kovin rasitettiin, sanoin, että
ne olivat liian nuoria ja että ne eivät vielä milloinkaan olleet
jyväkuormia vetäneet.

Koettaen hämillä-oloansa salata, arveli Kohlhas, ettei Herse tässä


ollut selvää totuutta puhunut, sillä jo keväällä olivat hevoset olleet
joitakuita kertoja kuorman edessä.

— Olisithan helposti saattanut linnassa, jatkoi hän, jossa kuitenkin


olit jonkinlaisena vieraana, käyttäytyä vähän sävyisämmin, kun oli
tärkeätä saada elot pian korjuun.

— Niinhän minä teinkin, hyvä isäntä, sanoi Herse; minä ajattelin,


kun he osoittivat tyytymättömyyttä, ettei siitä juuri taitaisi hevosille
vahinkoa olla; kolmantena aamupäivänä valjastin minä ne ja ajoin
kolme viljakuormaa niillä latoon.
Kohlhas loi hämmästyneenä katseensa maahan sanoen: Siitä
eivät minulle ole mitään virkanneet, Herse!

Herse vannoi, että asia niin oli. Minun niskoittelemiseni oli siinä,
sanoi hän, ett'en minä tahtonut valjastaa hevosiani uudestaan
puolen päivän aikana, kun ne tuskin olivat ehtineet mitään syödä,
sekä siinä, että minä vastasin linnanvoudille ja hoitajalle, kun he
ehdottelivat tahtovansa antaa minulle rehuja ilmaiseksi, jotta minä
voisin pistää teidän antamanne rahat omaan taskuuni, kaikessa
muussa palvelevani heitä, mutta en tässä, ja kääntäen heille selkäni
menin matkaani.

— Mutta ei suinkaan sinua senvuoksi Tronkenburg'ista kartoitettu?

— Ei, se tapahtui toisen hairauksen vuoksi; illalla, näetten, vietiin


kahden Tronkenburg'iin tulleen ritarin hevoset talliin ja minun
hevoseni sidottiin tallin oven pieleen; ja kun minä otin hevoset
linnanvoudilta, joka ne siihen oli asettanut, ja kysyin, mihin eläimet
nyt sijoitettaisiin, osoitti hän minulle, ruoteista ja laudoista tehdyn
sikoläätin linnan muurin vieressä.

— Aattelit varmaankin paikan olleen niin huonon hevosille, että se


oli enemmän sikoläätin, kuin tallin kaltainen?

— Se oli sikoläätti, isäntä hyvä, totta tosiaan, oikea sikoläätti,


jossa siat juoksivat edes takaisin ja jossa minä en voinut suorana
seisoa.

— Ehkäpä ei ollut muuta suojaa hevosille, ja ritarien hevosilla oli


ehkä tavallansa etuoikeus?
— Tila oli kyllä ahdas, sanoi Herse matalammalla äänellä, ja
linnassa oli seitsemän ritaria. Jos te olisitte ollut siellä, olisitte ehkä
saaneet asetetuksi hevoset vähän tiuhempaan. Minä tahdoin
kuulustella tallia kylästä, mutta linnanvouti vastasi, että hänen täytyi
pitää hevoset näkyvissänsä ja ett'en minä saisi viedä niitä linnasta
pois.

— Hm! Mitä sinä sitten teit?

— Kun linnanhoitaja sanoi, että nuot kaksi vierasta viipyisivät


ainoastaan yön siellä ja aamulla heti lähtisivät ratsastamaan
eteenpäin, vein minä hevoset läättiin. Mutta seuraava päivä meni,
eikä mitään muutosta tullut, ja kolmantena päivänä kuulin, että herrat
jäisivät linnaan muutamaksi viikoksi.

— Mutta ei suinkaan sikoläätissä ollutkaan niin huono oltava, kuin


ensin arvelit?

— Ei, totta se! Kun minä olin paikan puhdistanut, kävi kyllä päinsä
siellä olo. Minä maksoin piialle vähän, että hän muuttaisi siat pois, ja
toimitin niin, että hevoset voivat esteettömästi seisoa päivällä; minä
otin, näetten, aamuisin laudat ruoteilta ja asetin ne jälleen illalla
paikalleen, hevoset kurkistelivat nyt katon aukosta, kuten hanhet, ja
katselivat Kohlhasenbrück'iin tahi muihin paikkoihin päin, missä olisi
ollut parempi olla.

— No, mutta minkä kumman tähden he sinut sitten sieltä pois


ajoivat?

— Niin, isäntä, senvuoksi, että tahtoivat päästä minusta eroon,


sillä he eivät saaneet kiusata hevosia, niinkauan kuin minä olin
siellä. Jokapaikassa, kartanolla ja linnanpihassa, osoittivat he
minulle äkäistä muotoa ja olivat aina ilkeäpintaiset minua vastaan, ja
kun minä ajattelin: olkaa, miten olettekin, minä en siitä välitä mitään,
niin käyttivät he ensi tilaisuutta hyväksensä ja ajoivat minut pois.

— Mutta minkä johdosta? Tottahan heillä jotakin syytä siihen täytyi


olla?

— Se on tietty, isäntä, ja hyvin pätevä syy heillä olikin! Illalla


toisena päivänä, jonka olin sikoläätissä viettänyt, irroitin minä
hevoset, jotka siellä olivat likaantuneet, ja aikomukseni oli niitä
uittaa; mutta juuri kun minä pääsen linnanportille, kuulen minä
linnanvoudin ja -hoitajan ryntäävän ulos linnantuvasta minun perääni
palvelijoineen, koirineen, karikot kädessä, ja huutavan ikäänkuin
mielipuolina: Ottakaa kiinni tuo jankuttaja! Portinvartia asettuu tielle
minun eteeni, ja kun minä kysyn häneltä, mitä tuo raivoisa joukko,
joka juoksee minua kohden, tahtoo ja mitä sillä on mielessä, vastaa
linnanvouti: mitäkö me tahdomme! ja tarttuu molempain hevosten
ohjaksiin. Mihin sinä viet hevoset? kysyy linnanvouti ja käy minua
rinnuksiin. Minä vastaan: aioin mennä uittamaan niitä; luuletteko te
herra, että minä…. Uittamaan! kiljuu linnanvouti, kyllä minä opetan
sinut uimaan, karkuri, ja samassa tempaa hän ja linnanhoitaja, joka
oli käynyt kiinni jalkaani, minut alas hevosen selästä, niin että minä
putoan pitkää pituuttani rapaan. Karkuri! mitenkä te voitte semmoista
luulla, huudan minä; onhan tallissa vielä jälellä minun omaa
tavaraani: hevosloimi, silat ja palttinapakka! Mutta samassa kun
linnanhoitaja kulettaa pois hevoset, syöksyvät vouti ja palvelijat
minun kimppuuni potkien ja suomien minua ruoskilla ja sauvoilla, niin
että minä näännyn puolikuolleena maahan linnanportin taakse! Ja
kun minä kysyn: Mihinkä te hevoset viette? ja koetan nousta
pystyyn, kiljuu linnanvouti: Ulos sinä linnanpihalta! ja huudetaan, ot'
kiin', Musti! ot' kiin', Tuuna! ot' kiin', Pilkki! ja enemmän kuin tusina

You might also like