0% found this document useful (0 votes)
85 views

[Ebooks PDF] download Fundamentals Of Python: Data Structures 2nd Edition Kenneth A. Lambert full chapters

Kenneth

Uploaded by

augleediva7d
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views

[Ebooks PDF] download Fundamentals Of Python: Data Structures 2nd Edition Kenneth A. Lambert full chapters

Kenneth

Uploaded by

augleediva7d
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Download the Full Version of textbook for Fast Typing 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/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at 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/

textboxfull.com

Data Structures & Algorithms in Python John Canning

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

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

textboxfull.com

Fundamentals of Structural Analysis Kenneth M. Leet

https://textbookfull.com/product/fundamentals-of-structural-analysis-
kenneth-m-leet/

textboxfull.com
Fundamentals of Music Processing: Using Python and Jupyter
Notebooks 2nd Edition Meinard Müller

https://textbookfull.com/product/fundamentals-of-music-processing-
using-python-and-jupyter-notebooks-2nd-edition-meinard-muller/

textboxfull.com

Data Structures with C Programming 2nd Edition Anil Kumar


Yadav

https://textbookfull.com/product/data-structures-with-c-
programming-2nd-edition-anil-kumar-yadav/

textboxfull.com

Python for Data Science 2nd Edition John Paul Mueller

https://textbookfull.com/product/python-for-data-science-2nd-edition-
john-paul-mueller/

textboxfull.com

Matplotlib for Python Developers Effective techniques for


data visualization with Python 2nd Edition Yim

https://textbookfull.com/product/matplotlib-for-python-developers-
effective-techniques-for-data-visualization-with-python-2nd-edition-
yim/
textboxfull.com

Interpreting LISP: Programming and Data Structures 2nd


Edition Gary D. Knott (Auth.)

https://textbookfull.com/product/interpreting-lisp-programming-and-
data-structures-2nd-edition-gary-d-knott-auth/

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

Fundamentals of Python:
Data STRUCTURES

Kenneth A. Lambert

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

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

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

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

Product Team Manager: Kristin McNary

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

Vice President, Strategic Marketing Services:


Jennifer Baker Library of Congress Control Number: 2018956860

Marketing Director: Michele McTighe

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

Director, Content Delivery: Patty Stephan


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

Cengage products are represented in Canada by


Nelson Education, Ltd.

To learn more about Cengage platforms and services, register or


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

Notice to the Reader


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

Printed in the United States of America


Print Number: 01     Print Year: 2018

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

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

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


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

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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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


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

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

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


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

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


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

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

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


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

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


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

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

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


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

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

What You’ll Learn


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

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

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

Organization of this Book


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

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

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

New in this Edition


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

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

Instructor Companion Site


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

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


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

xvi

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

We Appreciate Your Feedback


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

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

About the Author


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

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

After completing this chapter, you will be able to:

Write a simple Python program using its basic structure


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

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

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

Basic Program Elements


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

Programs and Modules


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

An Example Python Program: Guessing a Number


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

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

import random

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

if __name__ == "__main__":
main()

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


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

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

Editing, Compiling, and Running Python Programs


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

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

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

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

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

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

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

Spelling and Naming Conventions


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

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

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

Type of Name Examples


Variable salary, hoursWorked, isAbsent

Constant ABSOLUTE_ZERO, INTEREST_RATE

Function or method printResults, cubeRoot, input

Class BankAccount, SortedSet

Table 1-1 Examples of Python Naming Conventions

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

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

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

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

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

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

Operators and Expressions


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

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

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

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

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

The print Function


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

The input Function


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

Type Conversion Functions and Mixed-Mode Operations


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

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


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

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

Optional and Keyword Function Arguments


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

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

its arguments are displayed. To prevent this from happening, you can give the optional
­argument end a value of the empty string, as follows:
print("The cursor will stay on this line, at the end", end = "")

Required arguments have no default values. Optional arguments have default values and
can appear in any order when their keywords are used, as long as they come after the
8
required arguments.
For example, the standard function round expects one required argument, a rounded num-
ber, and a second, optional argument, the number of figures of precision. When the second
argument is omitted, the function returns the nearest whole number (an int). When the
second argument is included, the function returns a float. Here are some examples:
>>> round(3.15)
3

>>> round(3.15, 1)
3.2

In general, the number of arguments passed to a function when it is called must be at least
the same number as its required arguments.
Standard functions and Python’s library functions check the types of their arguments when
the function is called. Programmer-defined functions can receive arguments of any type,
including functions and types themselves.

Variables and Assignment Statements


A Python variable is introduced with an assignment statement. For example:
PI = 3.1416

sets PI to the value 3.1416. The syntax of a simple assignment statement is:
<identifier> = <expression>

Several variables can be introduced in the same assignment statement, as follows:


minValue, maxValue = 1, 100

To swap the values of the variables a and b, you write:


a, b = b, a

Assignment statements must appear on a single line of code, unless the line is broken after
a comma, parenthesis, curly brace, or square bracket. When these options are unavailable,
another means of breaking a line within a statement is to end it with the escape symbol \.
You typically place this symbol before or after an operator in an expression. Here are some
admittedly unrealistic examples:
minValue = min(100,
200)
product = max(100, 200) \
* 30
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

When you press Enter after a comma or the escape symbol, IDLE automatically indents the
next line of code.

Python Data Typing


9
In Python, any variable can name a value of any type. Variables are not declared to have a
type, as they are in many other languages; they are simply assigned a value.
Consequently, data type names almost never appear in Python programs. However, all
­values or objects have types. The types of operands in expressions are checked at run time,
so type errors do not go undetected; however, the programmer does not have to worry
about mentioning data types when writing code.

import Statements
The import statement makes visible to a program the identifiers from another module.
These identifiers might name objects, functions, or classes. There are several ways to
express an import statement. The simplest is to import the module name, as in:
import math

This makes any name defined in the math module available to the current module, by using
the syntax math.<name>. Thus, math.sqrt(2) would return the square root of 2.
A second style of importing brings in a name itself, which you can use directly without the
module name as a prefix:
from math import sqrt
print(sqrt(2))

You can import several individual names by listing them:


from math import pi, sqrt
print(sqrt(2) * pi)

You can import all names from a module using the * operator, but that is not usually
­considered good programming practice.

Getting Help on Program Components


Although the Python website at www.python.org has complete documentation for the
Python language, help on most language components is also readily available within
the Python shell. To access such help, just enter the function call help(<component>) at the
shell prompt, where <component> is the name of a module, data type, function, or method.
For example, help(abs) and help(math.sqrt) display documentation for the abs and
math.sqrt functions, respectively. Calls of dir(int) and dir(math) list all the operations
in the int type and math module, respectively. You can then run help to get help on one of
these operations.
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

Note that if a module is not the built-in module that Python loads when the shell starts, the
programmer must first import that module before asking for help on it. For example, the
following session with the shell displays the documentation for the numberguess program
discussed earlier in this chapter:
>>> import numberguess
10 >>> help(numberguess)
Help on module numberguess:
NAME
numberguess
DESCRIPTION
Author: Ken Lambert
Plays a game of guess the number with the user.
FUNCTIONS
main()
Inputs the bounds of the range of numbers,
and lets the user guess the computer’s number until
the guess is correct.
FILE
/Users/ken/Documents/CS2Python/Chapters/Chapter1/numberguess.py

Control Statements
Python includes the usual array of control statements for sequencing, conditional execu-
tion, and iteration. A sequence of statements is a set of statements written one after the
other. Each statement in a sequence must begin in the same column. This section examines
the control statements for conditional execution and iteration.

Conditional Statements
The structure of Python’s conditional statements is similar to that of other languages. The
keywords if, elif, and else are significant, as is the colon character and indentation.
The syntax of the one-way if statement is:
if <Boolean expression>:
<sequence of statements>

A Boolean expression is any Python value; as mentioned earlier, some of these count as
False, and the others count as True. If the Boolean expression is True, the sequence of
statements is run; otherwise, nothing happens. The sequence of (one or more) statements
must be indented and aligned at least one space or tab (typically four spaces). The colon
character is the only separator; if there is only one statement in the sequence, it may imme-
diately follow the colon on the same line.
The syntax of the two-way if statement is:
if <Boolean expression>:
<sequence of statements>
else:
<sequence of statements>
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.
Control Statements

Note the indentation and the colon following the keyword else. Exactly one of these two
sequences of statements will be run. The first sequence is run if the Boolean expression is
True; the second sequence is run if the Boolean expression is False.

The syntax of the multiway if statement is:


if <Boolean expression>:
<sequence of statements>
11
elif <Boolean expression>:
<sequence of statements>
...
else:
<sequence of statements>

A multiway if statement runs exactly one sequence of statements. The multiway if


s­ tatement includes one or more alternative Boolean expressions, each of which follows the
keyword elif. You can omit the trailing else: clause.
The next example outputs the appropriate answer to a question about the relative sizes of
two numbers:
if x > y:
print("x is greater than y")
elif x < y:
print("x is less than y")
else:
print("x is equal to y")

Using if __name__ == "__main__"


The numberguess program discussed earlier includes the definition of a main function and
the following if statement:
if __name__ == "__main__":
main()

The purpose of this if statement is to allow the programmer either to run the module as a
standalone program or to import it from the shell or another module. Here is how this works:
every Python module includes a set of built-in module variables, to which the Python vir-
tual machine automatically assigns values when the module is loaded. If the module is being
loaded as a standalone program (either by running it from a terminal prompt or by loading it
from an IDLE window), the module’s __name__ variable is set to the string "__main__".
Otherwise, this variable is set to the module’s name—in this case, "numberguess". Either
assignment is accomplished before any of the code within the module is loaded. Thus, when
control reaches the if statement at the end of the module, the module’s main function will be
called only if the module has been launched as a standalone program.
The if __name__ == "__main__" idiom is useful when developing standalone program
modules, because it allows the programmer to view help on the module just by importing it
into the shell. Likewise, the programmer can use this idiom in supporting modules to run a
test bed function during module development within IDLE.
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.
Exploring the Variety of Random
Documents with Different Content
A cette période de Kiev appartiennent les premiers succès
sérieux de la musique nationale (l’opéra de Lyssenko, « La nuit de
Noël ») et aussi l’essor du théâtre ukrainien, grâce surtout aux efforts
de Kropyvnytsky et de Starytsky, sans compter les progrès
considérables dans les belles lettres (les nouvelles de Levytsky-
Netchouï, celles de Konisky, les poésies de Roudansky, etc.).
Mais le succès provoque l’envie : une opposition acharnée des
partisans de « l’unité du peuple russe » se déchaîne dans la presse
et envahit le monde officiel. A la tête du mouvement national de Kiev,
il n’y avait guère que des modérés qui saisissaient toutes les
occasions pour en souligner le caractère non-politique, pour en faire
ressortir la valeur civilisatrice, en démontrer les fondements
scientifiques ; malgré qu’ils se montrassent adverses au mouvement
révolutionnaire, le gouvernement continuait de prêter l’oreille aux
ukrainophobes. A la suite d’une dénonciation, faite par un des
suppôts jurés de « l’unité », M. Jousefovytch, contre la « Section du
Sud-Ouest » et ses membres, dans laquelle les idées ukrainiennes
étaient accusées de servir de manteau au « socialisme le plus pur »
et aussi — quoique le rapprochement dût paraître bien
extraordinaire — à l’intrigue autrichienne, le gouvernement central
intervint. Une enquête minutieuse ne découvrit dans les publications
incriminées aucune trace compromettante, néanmoins la
« commission extraordinaire », instituée par les autorités de
Pétersbourg, jugea qu’il fallait arrêter la productivité littéraire
ukrainienne, comme « une atteinte à l’unité et à l’intégrité de la
Russie ». Conformément à cet avis, dans l’été de 1876, juste au
moment où la Russie retentissait de clameurs enthousiastes,
présageant la délivrance des Slaves des Balkans du joug de la
Turquie, fut rendu le fameux ukase (à Ems, 18 (30) mai), qui mit
pour longtemps dans de lourdes chaînes le mouvement ukrainien en
Russie.
Cet édit, qui resta en vigueur pendant trente ans et a acquis ainsi
une triste célébrité, prescrivait que pour l’avenir aucune publication
« en dialecte petit-russien », éditée à l’étranger, ne pourrait être
introduite en Russie sans une autorisation spéciale. Dans l’empire
même, toutes œuvres originales ou traductions en ce « dialecte »
étaient sévèrement interdites, à l’exception des documents
historiques, à condition de conserver l’orthographe de l’original, et
des œuvres de pure littérature, à condition d’observer
soigneusement les règles de « l’orthographe russe généralement en
usage ». De même étaient prohibées toutes représentations
scéniques, toutes conférences et même la publication des textes des
œuvres musicales « en dialecte petit-russien ».
Il est clair que l’ukase ne trahissait aucune douceur pour la
culture ukrainienne. Cependant la censure et les fonctionnaires
reçurent encore de nombreuses instructions supplémentaires qui
laissaient à l’interprétation assez de marge pour que l’on pût
aggraver ces prohibitions. Par exemple, quoique l’édit n’eût pas
parlé de la presse quotidienne, il était admis dans la pratique qu’elle
était également interdite. Il en était de même pour les traductions,
quoique l’ukase semblât bien les autoriser. On ne pouvait non plus
éditer de livres pour les enfants. On recommanda aux censeurs de
se servir de tous les moyens pour restreindre en général cette
littérature « à visées exclusivement étatistes ». Ils biffèrent partout le
mot « Ukraine », non seulement l’expression : « la langue
ukrainienne », mais aussi celle-ci : « la langue petite-russienne », car
ce n’était, paraît-il, qu’un dialecte.
Il se forma tout une jurisprudence chicanière autour de ces
prohibitions quelquefois grotesques ; car que ne pouvait-on pas tirer,
par exemple, de cette exigence irréalisable dans la pratique, que les
mots ukrainiens fussent écrits selon l’orthographe russe ? Quelques
censeurs étendirent cette règle bizarre non seulement à
l’orthographe phonétique, mais à la morphologie. De peur qu’on
n’oubliât de se prévaloir de quelque prétexte, les manuscrits
ukrainiens étaient encore soumis à une double censure, d’abord
examinés par les comités locaux, ils étaient en outre envoyés au
bureau central. Cela causait des désagréments sans nombre aux
auteurs et aux éditeurs, les courages mal aguerris s’énervaient, bien
des projets littéraires ne purent voir le jour. Néanmoins ces mesures
n’atteignirent qu’à moitié leur objet, qui consistait à enrayer la
propagation dans les masses des lumières et de la conscience
nationale.
Le mouvement littéraire ne devait plus s’arrêter. Dans le quart de
siècle qui suivit le premier arrêt de 1847–56, il n’avait fait que
s’accroître et prendre de l’influence. Le tranchant des représailles
s’émoussa par l’usage trop souvent répété. Cette fois encore, en
1876, il y eut des expulsions, des suspensions, on supprima des
organisations — en premier lieu la Section du Sud-Ouest — mais les
gens à la longue avaient fini par apprendre à s’accommoder aux
circonstances. On avait « des positions préparées d’avance » — en
Galicie.
En effet les relations nouées par les gens de lettres et les
hommes politiques de la Grande Ukraine avec les éditeurs et les
groupes galiciens en 1861–62, loin de se rompre, n’avaient pas
cessé de se raffermir et même de s’étendre. La menace
gouvernementale étant toujours suspendue sur les têtes, on avait
pris des mesures pour y parer. Grâce aux efforts communs, fut
fondée, en 1873, une nouvelle institution, « La Société
Chevtchenko », à l’aide de fonds ramassés dans la Grande Ukraine.
On acheta pour elle une imprimerie qui devait être un instrument de
culture pour l’avenir. La revue mensuelle « Pravda », fondée à
Léopol en 1867, devint l’organe commun des écrivains de la Galicie
et de l’Ukraine. Plus tard elle céda la place à une revue
hebdomadaire, la « Zoria ». Les Ukrainiens de Russie, privés chez
eux de la possibilité d’avoir un organe qui leur appartînt, prêtaient
leur concours à ces publications. Ainsi donc toutes les difficultés
créées par l’ukase de 1876 eurent, entre autres résultats, de faire
transporter le flambeau national sur le sol galicien où, au lieu de
s’éteindre, il brûlera d’un plus vif éclat que dans le passé.
XXXVII.
Les dernières décades du XIXe siècle.

L’ukase de 1876 devait rester en vigueur exactement trente ans,


mais il y avait plusieurs manières d’en appliquer les prescriptions,
dont quelques-unes étaient trop absolues pour pouvoir se maintenir
dans la pratique. Il se passa quelques années, pendant lesquelles
on ne permit ni spectacles, ni concerts ukrainiens et où les chansons
populaires étaient rendues dans une traduction française (!). En fin
de compte, les autorités locales et en tête les gouverneurs généraux
de Kiev et de Charkov firent entendre en haut lieu qu’il n’était point
raisonnable d’irriter ainsi la population et d’exposer l’administration
au ridicule. On permit les représentations scéniques ukrainiennes,
mais toujours avec des restrictions aussi bizarres
qu’embarrassantes, comme pour les livres. La censure fit de
véritables prouesses sur ce terrain : il n’était pas permis de jouer des
pièces qui fussent prises de la vie des classes supérieures, qui
touchassent en rien aux problèmes sociaux ou simplement
patriotiques. Les pièces autorisées devaient être données en même
temps que des œuvres russes ayant le même nombre d’actes, etc.
Le théâtre ukrainien supporta gaillardement cette oppression.
Les entrepreneurs se pliaient à toutes ces formalités ou les
éludaient, car la population manifestait un enthousiasme sans
bornes pour l’art dramatique national, qui justement s’épanouissait
rapidement. Toute une pléiade de dramaturges de talent créait alors
un style artistique ukrainien, qui se distinguait par un noble réalisme
dans le drame de genre ou le drame historique. Ils eurent d’ailleurs
beaucoup à faire pour relever le contenu d’un art à qui la censure ne
laissait que des matières insignifiantes. Malgré tout, la scène devint
un facteur précieux dans l’éducation des masses, à une époque où
la liberté de la presse et de la parole n’existait pas, où il n’y avait pas
d’écoles et presque pas de littérature.
A peu près dans le même temps où l’on permettait le théâtre
ukrainien à Kiev, on y donnait l’autorisation de publier une revue
consacrée à l’histoire de l’Ukraine (« Kievskaïa Starina », depuis
1882). Il fallut la publier en russe et placer à sa tête un écrivain qui
était persona grata auprès des autorités, mais qui l’était beaucoup
moins dans le peuple. Néanmoins l’énergie des lettrés en fit en peu
de temps une sorte de foyer national, dont l’horizon ne se borna pas
aux recherches scientifiques. Dès qu’elle put obtenir le droit de le
faire, elle publia des œuvres littéraires, s’intéressa aux questions de
la vie journalière et servit sous cette forme de succédané à la revue
ukrainienne que le gouvernement s’obstinait à ne pas autoriser.
N’était-ce point là la preuve de la vitalité du mouvement
national ? Il sembla que l’on n’eût qu’à planter un rameau desséché
dans le sol ukrainien, pour qu’on le vît fleurir et produire des fruits.
Et, quand même, ces perspectives étaient bien insignifiantes
comparées aux besoins d’un grand peuple, au dénuement de ces
millions de travailleurs obscurs, condamnés à la misère et à
l’ignorance. Et ce rayon d’espoir même était si menacé par la grande
ombre de la tutelle administrative qu’au lieu de satisfaire l’âme
ukrainienne, il y faisait naître l’inquiétude et la colère. D’autant plus
que tout près, au delà des poteaux jaunes et noirs de la frontière, les
compatriotes jouissaient d’une liberté assez limitée, il est vrai, mais
incomparablement plus large.
La constitution autrichienne de 1867 ne se distinguait pas par ses
hautes qualités. Elle avait été octroyée dans l’intention d’assurer une
influence aussi large que possible à l’aristocratie foncière et à la
bourgeoisie des villes aux dépens de la population paysanne ; le
système électif à deux degrés et à bulletin ouvert, laissait à
l’administration un rôle beaucoup trop grand dans les élections.
Bureaucratisme et domination de la noblesse polonaise se
complétaient mutuellement. Après une courte bouderie, qui suivit la
révolution de 1848, la noblesse était passée au gouvernement et
grâce à cette entente avait repris le pouvoir en Galicie.
L’administration était entre ses mains, ainsi que les municipalités
électives. Elle avait soin d’arranger les scrutins, pour que les
Ukrainiens ne passassent qu’en nombre infime, encore fallait-il que
ce soient des gens « modérés ». C’est pourquoi la population
ukrainienne, aussi nombreuse que la polonaise dans la Galicie
entière, n’était représentée au parlement que par une dizaine de
députés, et n’avait dans la diète territoriale que 10% des sièges. Les
conseils d’arrondissement étaient formés de la même façon. Toute
cette machinerie était donc entre les mains de la noblesse
polonaise, qui s’en servait pour brider l’élément ukrainien, empêcher
le développement économique et intellectuel des masses
paysannes, barrer le chemin du pouvoir aux autres nationalités et
assurer la prépondérance de l’élément polonais.
Tous les efforts des hommes politiques ukrainiens pour se
soustraire à cette domination restaient sans résultat. Les
coquetteries du gouvernement ne se répétèrent pas, de sorte que,
bon gré mal gré, on fut obligé de prendre au parlement la voie de
l’opposition. Les modérés, pour la plupart membres du haut clergé
ou de la bureaucratie, furent obligés de céder leurs sièges à des
éléments plus radicaux, qui s’unirent d’abord dans le parti populaire
(narodovtsi) après s’être séparés des conservateurs d’extrême-
droite (vers 1885). Plus tard l’aile gauche de ce parti se détacha à
son tour pour former le parti radical (1889).
Michel Drahomanov, dont nous avons mentionné le rôle de
leader avancé du mouvement de Kiev, devint l’esprit directeur de
cette opposition radicale. Originaire du gouvernement de Poltava,
élevé à Kiev, historien spécialisé, voilà l’homme qui pendant un quart
de siècle sera un des guides principaux de la politique en Ukraine.
Dénoncé au gouvernement russe pour son activité en Galicie et ne
trouvant pas dans ce dernier pays des garanties suffisantes de la
liberté de propagande, il s’établit à Genève, où, avec quelques
autres émigrés ukrainiens il commença une campagne énergique et
grosse de conséquences. La revue fondée par eux, la « Hromada »
(1878), fut la première tribune, où les patriotes ukrainiens, et en
première ligne Drahomanov lui-même, purent exposer ouvertement
et motiver abondamment leur programme. Ils reprirent les idées de
la Confrérie de Cyrille et de Méthode, en y apportant les
changements nécessaires après trente ans d’évolution et, à
l’exemple de leurs prédécesseurs, ils conduisirent le mouvement
national vers le démocratisme et le socialisme, essayant, à l’aide de
ce flambeau, de jeter de la lumière sur les aspirations sociales et
politiques d’antan, de faire voir dans les ancêtres les précurseurs
des démocrates et des socialistes modernes, de rattacher le passé
au présent. C’est ce qui était exprimé métaphoriquement dans
l’article-programme, dans les premières pages de la « Hromada » :
« Nos lettrés sauront-ils saisir le bout de ce fil qui se file de lui-
même dans notre monde paysan ? Sauront-ils le raccorder à ce qui
a été tissé pendant les XVIIe et XVIIIe siècles, dans la pensée des
gens dont l’histoire ne s’est pas interrompue ? Sauront-ils rattacher
ce fil, filé dans l’obscurité et le silence, qui est plus souvent un désir
qu’une pensée claire, au grand réseau d’idées scientifiques et
sociales du monde européen ? Voilà quelle doit être la tâche des
intellectuels de l’Ukraine. »
Partant de là, Drahomanov formulait ainsi le programme
ukrainien : fédéralisme dans la politique, liberté individuelle dans la
vie sociale, socialisme dans la vie économique, rationalisme et
réalisme dans les sciences et dans les arts. Sur ces bases, il
critiquait vivement les opportunistes, les conservateurs et les
chauvins de la Galicie et de la Grande Ukraine, il les invitait à un
travail politique et civilisateur conséquent, animé d’un large
démocratisme national dans sa forme et universel dans son esprit. Il
se montra l’adversaire des méthodes révolutionnaires pratiquées
alors en Russie et désapprouvait surtout les actes de terrorisme. Il
s’adressait surtout aux intellectuels de Galicie, puisque la presse de
ce pays le lui facilitait, tandis que la presse russe était soumise à la
censure. Ce fut là aussi que se firent le mieux sentir les résultats de
son influence. Nous y trouvons ses partisans les plus ardents : O.
Terletsky, M. Pavlyk et surtout Ivan Franko, le plus noble
représentant de l’Ukraine galicienne, poète, savant et publiciste des
plus pénétrants et des plus féconds (1856–1916). Ces écrivains se
proposent de réaliser le programme de Genève sur le sol de la
Galicie, ils attaquent énergiquement les restes du vieil opportunisme
et du cléricalisme, ils luttent contre l’éloignement que les générations
précédentes avaient montré envers le peuple, et s’imposent comme
tâche immédiate la formation d’un parti paysan par excellence, ayant
pour but l’instruction des masses campagnardes et leur organisation
politique.
Puisque en Ukraine Occidentale aussi bien qu’en Ukraine
Orientale la vie ukrainienne s’était réfugiée presque exclusivement
dans les campagnes, il fallait que le parti paysan prît sur lui les
tâches nationales et que par conséquent il obtînt la prépondérance
dans la représentation politique du pays. Aussi sa formation n’alla-t-
elle pas sans une critique énergique des tendances
antidémocratiques des partis de droite ukrainiens. Ces divergences
étaient surtout criantes en Galicie. Le parti nationaliste ne pouvait
abandonner ses anciens rêves d’obtenir la faveur du gouvernement
et, comme le gouvernement était représenté ici par la bureaucratie
ou pour mieux dire la noblesse polonaise, ses leaders essayèrent de
s’entendre avec elle aux prix de certaines concessions (1890).
Ce pas imprudent souleva l’indignation populaire et ce fut à cette
occasion que se forma le susdit parti radical paysan, à la tête duquel
se mirent les partisans de Drahomanov, réclamant énergiquement
une opposition intransigeante contre le régime de la noblesse. Ces
querelles produisirent dans la population et entre les partis
ukrainiens une tension sans exemple dans les annales politiques du
pays. La Grande Ukraine fut entraînée dans ces débats ; ce fut un
flot de discussions sur les questions politiques et sociales, sur
l’opportunisme dans la vie publique et le conservatisme national.
A défaut de presse dans la Grande Ukraine, les revues et les
journaux galiciens deviennent l’arène animée où s’échangent les
idées, où se rencontrent et s’entrechoquent les tendances diverses.
On se prononce ouvertement sur les questions vitales concernant
l’Ukraine Orientale, et on ne manque pas de se répandre en
critiques acerbes contre le régime de la Russie et contre sa politique
hostile aux nationalités. Le gouvernement de Pétersbourg peut bien
fermer ses frontières aux publications galiciennes, mais elles
pénètrent dans l’intérieur, malgré toutes les précautions, et y attisent
l’opposition radicale et démocratique dans les populations.
XXXVIII.
Au tournant du siècle. (1898–1906.)

En Russie, l’administration eut beau faire et, en Galicie, le


« travail organique » des Polonais se continuer, il n’en est pas moins
vrai que, vers la fin du siècle, le mouvement ukrainien avait pris une
ampleur que l’on aurait eu peine à s’imaginer vingt ans auparavant.
Ses conquêtes ne se bornaient pas au domaine politique, il
manifestait aussi sa puissance dans la littérature, les sciences et les
arts. Il ne se contente plus de prouver théoriquement son droit à
l’existence, mais il passe au travail d’édification sur le terrain de la
pratique.
En Galicie, la chaire d’histoire à l’université de Léopol, que les
patriotes ukrainiens étaient parvenus à obtenir, leur servit de point
de départ pour étendre leurs ambitions ; ils se rappelèrent que le
gouvernement autrichien avait promis que cette université tout
entière serait l’apanage des Ukrainiens, comme celle de Cracovie
celui des Polonais et que, par conséquent, cette institution n’était
passée que de fait entre des mains étrangères. La lutte s’enflamma
à ce sujet ; pour le moment on réclama un certain nombre de chaires
séparées, pour en arriver peu à peu à une université ukrainienne. Il
fallait trouver des professeurs : les étudiants ne se contentent pas
d’organiser des manifestations en masse, pour réclamer leurs droits,
mais ils se livrent aussi à un travail scientifique intense. L’ancienne
« Société Chevtchenko », dont nous avons mentionné la fondation à
Léopol par les patriotes de la Grande Ukraine, se transforme en une
institution scientifique, se réorganise sur le modèle des Académies
des sciences de l’Europe et peut bientôt leur être comparée. Autour
d’elle se groupent les savants des deux Ukraines qui contribuent à
ses publications. (L’auteur de ces lignes, ukrainien originaire de
l’Ukraine Orientale, chargé de la chaire d’histoire nouvellement
créée, a eu l’honneur de présider pendant vingt ans aux destinées
de cette société.)
Le peuple lit et s’intéresse à lire dans les salles de lecture que
l’association « Prosvita » ouvre dans tout le pays. Les belles-lettres
s’enrichissent alors d’une série de talents brillants, qui ne le cèdent
en rien aux écrivains de l’Europe. Ils surgissent dans la Grande
Ukraine aussi bien qu’en Ukraine Occidentale, qui n’avait pas
jusqu’ici été féconde à cet égard ; ce sont, après Fedkovitch et
Franko déjà nommés, les romanciers V. Stefanyk, Z. Martovytch, O.
Kobylanska, pour ne citer que ceux-là et, en Grande Ukraine,
Tobilevitch, Kotsiubynsky, Samiylenko, Lessia Oukaïnka et d’autres
encore. Le centième anniversaire de la renaissance de la littérature
ukrainienne, à compter de 1798, année de l’apparition de l’Énéïde
de Kotlarevsky, fut célébré en Galicie au milieu de l’enthousiasme
délirant des foules et donna l’occasion de jeter un regard en arrière
sur les progrès accomplis pendant un siècle, malgré les difficultés du
chemin. Les plus mauvais jours étaient passés, l’avenir s’ouvrait
plein de promesses. C’était une année de jubilés : celui de l’abolition
du servage en Autriche en 1848, celui de la grande insurrection de
1648. Aussi dans le prologue écrit à cette occasion par Franko, le
plus grand poète national alors en vie, on croyait entendre le son de
la trompette annonçant la prochaine insurrection populaire, la
prochaine révolution qui délivrerait l’Ukraine.
L’organisation et l’instruction des masses avaient fait dans les dix
dernières années d’énormes progrès. La grande majorité des
paysans constituait déjà une armée politique solidement organisée,
sur laquelle ses chefs pouvaient compter. Elle avait renversé une à
une, avec une ténacité et une discipline admirables, les barrières
élevées par la classe dirigeante polonaise. Son stoïcisme, son
abnégation trouvaient leur écho dans les œuvres des romanciers
galiciens (les nouvelles de Martovytch particulièrement sont les
fastes de ces héros obscurs).
A cet égard la Grande Ukraine était restée bien en arrière. Quels
que fussent les défauts de la constitution autrichienne, ils
n’approchaient en rien de l’arbitraire qui régnait en Russie, mettant à
l’instruction politique des masses et à leur éducation nationale des
obstacles insurmontables. Les succès des intellectuels de la Galicie
étaient pour ceux de la Grande Ukraine une sorte de reproche
vivant, une source intarissable d’indignation contre un régime
oppresseur.
Ce même anniversaire de la renaissance, qui avait « des
positions préparées d’avance » en Galicie, donna lieu en Russie à
une manifestation jusque-là sans exemple, lors de l’inauguration à
Poltava du monument de Kotlarevsky, originaire de cette ville.
L’administration permit seulement aux délégués venus de Galicie de
prononcer à la cérémonie des discours en ukrainien, tandis que cela
restait interdit aux gens du pays. Ces derniers déchirèrent
ostensiblement les adresses qu’ils apportaient et se refusèrent à
prendre la parole. Et le plus remarquable pour l’époque c’est que
cette démonstration resta impunie !
D’ailleurs les autorités s’étaient lassées en reconnaissant leur
impuissance à arrêter le mouvement. D’année en année il se faisait
des brèches toujours plus grandes dans le système. La censure
devenait moins sévère, l’administration plus coulante dans la
pratique. On sentait que la conscience nationale des masses était
prête à se réveiller. Les partis politiques commençaient à
s’organiser : « le parti ukrainien révolutionnaire » est fondé en 1900
et prend pour devise : « L’Ukraine indépendante ». L’année 1904
amena la guerre russo-japonaise, dans laquelle l’observateur le plus
superficiel pressentait une répétition de la guerre de Crimée et le
commencement de la ruine de l’autocratisme. Le gouvernement en
eut conscience lui-même et commença de parler de sa « confiance
dans la population ». Au mois de décembre de la même année, le
conseil des ministres se souvint de la question ukrainienne et
exprima l’opinion que toutes les représailles pratiquées par le
gouvernement depuis trente ans, d’ailleurs impuissantes à atteindre
leur but, n’avaient été qu’une longue erreur : le mouvement ukrainien
ne présentait en réalité aucun danger pour l’état et toutes les
mesures prises pour l’enrayer n’avaient fait que nuire au
développement matériel et intellectuel des masses. Les autorités
compétentes consultées furent du même avis, notamment le
gouverneur général de Kiev, l’université de cette ville et celle de
Charkov et l’académie des sciences de Pétersbourg. Quelques
spécialistes de cette académie rédigèrent même un mémoire dans
lequel ils réfutaient impitoyablement les arguments qui avaient servi
à étayer la politique gouvernementale : la langue littéraire russe
n’était point une langue « pan-russe », familière à tous les Slaves
orientaux, c’était simplement la langue des Grands Russes ; elle ne
pouvait remplacer pour les Ukrainiens la langue maternelle qui avait
toujours existé à côté de la langue russe et avait droit à sa place au
soleil ainsi que littérature ukrainienne ou « petite-russienne ».
Le conseil n’avait pas encore eu le temps de prendre des
mesures en conséquence que le flot révolutionnaire se soulevait et
forçait le gouvernement à faire des concessions plus larges, qui
abolissaient les prescriptions spéciales contre le mouvement
ukrainien. Le 17 (30) octobre 1905, la constitution russe vit le jour ;
les « règlements provisoires sur la presse », publiés au mois de
novembre suivant, donnèrent la liberté aux journaux et d’autres
suivirent pour les publications non-périodiques (mai 1906), qui
annulèrent tacitement toutes les restrictions de 1876 et mirent les
langues allogènes sur le même pied que la langue russe. Les
Ukrainiens ne manquèrent pas d’en profiter, les premiers quotidiens
et les premières revues sortent des presses : vers le milieu de 1906,
on comptait déjà 35 publications périodiques en langue nationale.
Des sociétés pour propager l’instruction se forment en grand nombre
sur le modèle de la « Prosvita » de Galicie et sous le même nom. A
Kiev commence ses travaux une société ukrainienne des sciences
organisée à l’instar de celle de Léopol. Les livres s’emparent des
thèmes qui avaient été jusque-là prohibés en Russie. La « Revue
des sciences et des belles lettres », que l’on entretenait depuis dix
ans en Ukraine autrichienne était transportée de Léopol à Kiev.
Les élections au premier parlement de Russie, à la « Douma de
l’Empire », eurent lieu au printemps de 1905 ; elles envoyèrent à
Pétersbourg une proportion considérable de députés, qui
reconnaissaient le mouvement national et qui, au nombre d’environ
cinquante, formèrent à la Douma la fraction ukrainienne. Son
programme politique fut établi sur les traditions nationales :
fédéralisation de la Russie, établissement immédiat de l’autonomie
en Ukraine, enseignement dans la langue maternelle, emploi de
l’ukrainien dans l’administration et dans la vie publique, garantie des
intérêts nationaux des minorités.
XXXIX.
La réaction et la guerre. (1907–1916.)

Le peuple ukrainien allait-il enfin, après tant de siècles de


souffrances, entrer dans la voie du développement normal et guérir
des blessures qui avaient été infligées à sa vie nationale ? Il parut,
au moins par moments, qu’il en serait ainsi.
Les centres géographiques naturels de l’Ukraine redeviennent
aussi les foyers de la civilisation nationale. La liberté de parler, de se
réunir, de s’organiser donnait aux intellectuels la possibilité de
renverser les barrières de l’ignorance entre lesquelles la politique
russe avait parqué les masses. Jusque-là non seulement il ne
pouvait être question d’éduquer politiquement le peuple au moyen
de la presse, mais la moindre velléité d’un intellectuel à vouloir se
rapprocher des couches profondes pouvait lui coûter cher. Le
philosophe bien connu Lessevytch n’avait-il pas été banni en Sibérie
pour avoir introduit chez lui à la campagne la langue ukrainienne
dans l’école et éveillé les soupçons des autorités par son attitude
bienveillante envers les paysans ?
Mais maintenant il semblait que le livre et le journal pourraient
pénétrer dans les villages et ouvrir les yeux des travailleurs du sol
sur leurs besoins matériels et intellectuels ; que leurs frères, déjà
éclairés, pourraient aller s’informer auprès d’eux de leurs idées, de
leurs aspirations ; que les vœux de ces souffre-douleur jusque-là
muets se feraient entendre par la voix de leurs représentants à la
Douma ; que les organes de l’administration locale
s’autonomiseraient et se démocratiseraient. Ces succès
constitutionnels, fruits de la révolution, aiguillonnent les ardeurs en
Occident. La lutte reprend de plus belle en Autriche pour l’obtention
du suffrage égal, direct et au scrutin secret (il n’était ici qu’universel
et inégal) et les Ukrainiens de Galicie y prennent part avec une
énergie qu’anime la délivrance de leurs frères en Russie.
Dans l’empire des tzars, les chants de triomphe se turent bientôt.
Le chemin de la liberté n’était pas si court, ni si facile à monter. La
réaction ne se laissa pas abattre, elle tint bon sur toute la ligne. Le
manifeste constitutionnel était à peine promulgué, malgré les efforts
contraires des réactionnaires, que les pogromes commencèrent
aussitôt. Descentes de police, assassinats, condamnations à mort à
foison, les cours martiales accompagnèrent les élections. Quand la
Douma voulut élever sa voix contre ce régime pseudo-
constitutionnel, elle fut dissoute dans le troisième mois de son
existence et un grand nombre de ses membres furent jetés en prison
et privés de leurs droits politiques pour avoir protesté contre la
dissolution. La seconde Douma, contenant encore beaucoup trop de
députés d’opposition, fut également dissoute. On altéra la loi
électorale pour placer le scrutin sous l’œil de l’administration. Cette
tutelle se fit surtout sentir dans les provinces, dans les villages chez
les paysans. Leurs députés furent, en fait, désignés par le
gouvernement et l’Ukraine, qui avait été représentée dans la
première et la deuxième Douma par un nombre considérable de
députés, fut dans la troisième privée de toute représentation. Et si
ses mandataires n’avaient pu, grâce à une procédure législative des
plus compliquées, faire passer aucune loi favorable à ses
aspirations, que pouvait-elle espérer d’une majorité
gouvernementale et réactionnaire ? Il ne se trouva pas de voix
suffisantes pour appuyer une mesure aussi raisonnable que
l’introduction de la langue maternelle dans les écoles primaires de
l’Ukraine : la Douma se prononça pour l’introduction d’autres
langues dans ces écoles, mais l’ukrainien fut exclu. Dans ses dix
ans d’existence le parlement ne trouva rien à donner à ce pays.
En même temps l’arbitraire continuait de régner parce que
l’administration tenait à sa vieille routine et ne tenait aucun compte
des nouvelles lois, surtout lorsqu’elles ne cadraient pas avec ses
idées.
Ainsi, à les prendre à la lettre, les nouvelles prescriptions ne
faisaient aucune distinction entre la langue russe et les autres
langues de l’empire, entre une organisation russe et une
organisation allogène, mais la censure, la police et l’administration
avaient deux paires de balances : ce qui était permis en langue
russe ne pouvait paraître d’aucune manière en ukrainien. Cette
dernière langue opérait, à les en croire, d’une façon magique sur
l’imagination populaire, de sorte que la traduction du texte russe le
plus inoffensif pouvait avoir une portée incalculable. Les livres
ukrainiens, qui pouvaient maintenant être publiés sans censure
préalable, servaient de prétextes à des procès politiques dont l’issue
était souvent des plus funestes pour les auteurs. Les articles de
journaux qui ne pouvaient donner prise à la censure ou à
l’intervention du tribunal étaient toujours exposés aux chicanes de
l’administration. Conformément aux ordres secrets des autorités, les
quotidiens disparaissaient à la poste et n’arrivaient jamais aux
paysans et aux ouvriers. Leurs abonnés avaient à subir le
ressentiment de la bureaucratie. Les organisations ukrainiennes
n’obtenaient pas l’autorisation ou étaient plus tard fermées, au
mépris des lois. Cette pratique illégale trouvait l’approbation des
autorités suprêmes tant qu’elle était appliquée aux nationalités
indésirables.
Le sénat, ce gardien suprême des lois, décida en dernier appel,
sur une plainte des Ukrainiens de Poltava contre l’administration qui
ne leur permettait pas d’ouvrir leur section locale de la « Prosvita »,
que les organisations ukrainiennes n’étaient pas désirables même si
elles poursuivaient des buts légaux (1908). Plus tard le premier
ministre, Stolypine, déclara plus expressivement encore que le
gouvernement restait fidèle à la vieille politique de lutte contre tout
particularisme ukrainien et, en général, contre tout ce qui pouvait
porter atteinte à l’unité des Slaves orientaux. (Il faut noter que dans
cette circulaire, malgré la théorie officiellement admise de « l’unité du
peuple russe », les Ukrainiens sont clairement comptés parmi les
nationalités allogènes.) L’administration n’avait donc point besoin de
s’embarrasser des apparences de la légitimité. Ainsi, sans le
moindre motif, on ferma, en 1910, la plus importante société
d’instruction de l’Ukraine, la « Prosvita » de Kiev, ce qui fit une
pénible impression sur la population, habituée du reste à de pareilles
violations de droits.
En Autriche-Hongrie, les Ukrainiens avaient subi un échec, moins
brutal sans doute, mais tout aussi sensible. La réforme électorale
avait été adoptée, mais on l’avait défigurée dans la pratique pour
qu’elle fonctionnât au profit des nationalités et des classes sociales
privilégiées, de sorte que l’égalité devant le scrutin n’était plus
qu’une phrase vaine. Les arrondissements électoraux avaient été
répartis de telle façon, qu’il y avait un mandat pour 40 mille
Allemands, ou pour 80 mille Polonais, ou pour 150 mille Ukrainiens.
Ces derniers n’envoyèrent donc qu’un petit nombre de représentants
à ce « parlement populaire » qui ne répondit aucunement aux
espoirs qu’on avait placés en lui. Les dissensions entre les
nationalités prirent la prépondérance sur les luttes de classes et
firent échouer les projets de réforme. Le règlement des élections
pour les diètes provinciales avait été laissé à la compétence de ces
diètes mêmes. En Galicie les discussions à ce sujet furent si
acharnées, la lutte prit des formes si inouïes, que les relations entre
la population ukrainienne et la polonaise furent à jamais rompues.
C’est à cette époque que l’on commença à mettre en circulation
les bruits mensongers, d’après lesquels les organisations
ukrainiennes auraient reçu des subsides de l’Allemagne et que le
mouvement lui-même ne se maintenait qu’à l’aide du « mark
allemand ». Il est inutile d’ajouter que ces inventions étaient dénuées
de tout fondement, car, non seulement les Ukrainiens n’avaient
l’appui d’aucune puissance étrangère [30] , mais spécialement les
Allemands manquaient complètement d’intérêt pour leurs
aspirations, puisqu’ils les regardaient sous le même jour que les
publicistes et savants russes, à qui ils s’en rapportaient là-
dessus [31] . Néanmoins la presse nationaliste russe et polonaise fit
tout pour propager ces inepties et même le ministre Sazonoff ne
craignit pas de les répéter à la tribune de la Douma. Cela ne fit
qu’exaspérer les passions, qui devinrent incontrôlables lorsque la
guerre éclata.
[30] « Le mark allemand » servait en effet à gâter la
bonne humeur des politiciens polonais, mais d’une autre
manière. Au commencement du nouveau siècle, éclata
une grande grève d’ouvriers agricoles, qui fut étouffée par
l’administration polonaise. Les sociétés économiques
ukrainiennes organisèrent l’envoi en Allemagne, pour les
travaux de la saison, d’ouvriers agricoles ukrainiens. En
Galicie le niveau des salaires s’en ressentit au grand dam
des propriétaires fonciers polonais.
[31] Comme président de Société des sciences de
Kiev, je me rappelle un incident caractéristique. Cette
société proposa un échange de publications à d’autres
sociétés savantes, notamment à l’académie des sciences
de Berlin et leur envoya la collection complète de ses
publications. Les berlinois les renvoyèrent en remarquant
qu’elles ne présentaient pour eux aucun intérêt. Autant
qu’il m’en souvient, rien de pareil n’arriva même avec les
institutions russes ou polonaises !

On la sentait venir à la tension des rapports austro-russes,


depuis l’annexion de la Bosnie, et tous ceux que gênait le
mouvement ukrainien et qui voyaient d’un mauvais œil l’extension
qu’il avait prise pendant les dix dernières années, espéraient profiter
de l’occasion pour l’anéantir. Et ils étaient nombreux : chauvins
polonais en Galicie, chauvins russes dans la Grande Ukraine et tous
les renégats à qui la renaissance ukrainienne semblait un reproche
vivant. Aussi le premier coup de canon donna-t-il le signal d’une
atroce persécution.
En Russie, dès le début de la guerre, on supprima les journaux
ukrainiens. L’administration, usant largement des pouvoirs
extraordinaires que lui donnait la loi martiale, se mit à arrêter les
patriotes et à faire disparaître les organisations. La censure ne
manqua pas l’occasion de renouveler arbitrairement les anciennes
prescriptions que les publications ukrainiennes employassent
exclusivement l’orthographe russe et les mit par ses exigences dans
l’impossibilité de paraître.
La situation n’était guère plus supportable en Autriche.
L’administration polonaise en Galicie, la bureaucratie hongroise dans
les Carpathes, fortes de la puissance dont elles étaient revêtues en
temps de guerre, s’apprêtèrent à rendre inoffensifs à jamais les
intellectuels ukrainiens. Des centaines et des milliers de « suspects »
furent arrêtés, exilés dans les provinces occidentales, parqués dans
les camps de concentration ou jetés en prison. Lorsque les troupes
russes franchirent la frontière les autorités civiles quittèrent le pays,
mais les autorités militaires qui les remplacèrent pour un temps firent
fusiller à leur gré et sans aucune forme de procès.
L’occupation par les troupes russes, en automne 1914, fut encore
plus désastreuse. Le gouvernement du tzar ne crut-il pas tenir entre
les mains le centre du mouvement ukrainien, oubliant que la Galicie
n’avait été que son refuge depuis le décret de 1876, mais que son
véritable berceau était l’Ukraine même ? D’ailleurs, les imputations
calomnieuses d’une intrigue autrichienne ne continuaient-elles pas
de circuler ? N’étaient-elles pas devenues comme une sorte
d’hallucination des sphères officielles, qui auraient pourtant bien pu
vérifier les faits ? Mais ne s’agissait-il pas d’une simple vengeance ?
En tout cas les autorités russes se mirent à l’ouvrage avec
acharnement.
On exila les intellectuels ukrainiens et même des citadins et des
paysans qui semblaient avoir une certaine éducation. Femmes,
vieillards, enfants étaient traînés de prison à prison ou menés en exil
dans la Russie orientale ou la Sibérie, sans vêtements, sans
souliers, dans un état de détresse épouvantable. Les institutions et
les publications nationales furent supprimées, la langue ukrainienne
fut chassée de l’école et de l’administration, où l’on n’admit plus que
le polonais et le russe. Ce fut un rude coup et tout-à-fait inattendu
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like