Challenging Programming In Python A Problem Solving Perspective Habib Izadkhah pdf download
Challenging Programming In Python A Problem Solving Perspective Habib Izadkhah pdf download
https://ebookbell.com/product/challenging-programming-in-python-
a-problem-solving-perspective-habib-izadkhah-53052344
https://ebookbell.com/product/challenging-programming-in-python-a-
problem-solving-perspective-habib-izadkhah-55781650
https://ebookbell.com/product/adventures-in-snap-programming-learn-to-
design-exciting-and-challenging-programs-learning-computer-
programming-and-cs-principles-book-10-joshi-12199352
https://ebookbell.com/product/programming-puzzles-python-edition-the-
guide-to-sharpen-your-coding-skills-with-engaging-and-challenging-
puzzles-matthew-whiteside-189785258
https://ebookbell.com/product/challenging-history-race-equity-and-the-
practice-of-public-history-leah-worthington-44980716
Challenging Cases In Neurologic Localization An Evidencebased Guide
Joel I Shenker
https://ebookbell.com/product/challenging-cases-in-neurologic-
localization-an-evidencebased-guide-joel-i-shenker-45334398
https://ebookbell.com/product/challenging-formalization-in-education-
and-beyond-problems-and-solutions-for-traditional-and-online-learning-
peter-serdyukov-46091456
https://ebookbell.com/product/challenging-concepts-in-critical-care-
cases-with-expert-commentary-christopher-gough-46132554
https://ebookbell.com/product/challenging-cases-in-pulmonology-
massoud-mahmoudi-46170534
https://ebookbell.com/product/challenging-bias-in-forensic-
psychological-assessment-and-testing-1st-glenda-liell-46490046
Habib Izadkhah
Rashid Behzadidoost
Challenging
Programming in
Python: A Problem
Solving Perspective
Challenging Programming in Python: A Problem
Solving Perspective
Habib Izadkhah · Rashid Behzadidoost
Challenging Programming
in Python: A Problem
Solving Perspective
Habib Izadkhah Rashid Behzadidoost
Department of Computer Science Department of Computer Science
University of Tabriz University of Tabriz
Tabriz, Iran Tabriz, Iran
© The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature
Switzerland AG 2024
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether
the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse
of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and
transmission or information storage and retrieval, electronic adaptation, computer software, or by similar
or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book
are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or
the editors give a warranty, expressed or implied, with respect to the material contained herein or for any
errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland
v
vi Preface
in improving their Python programming skills. Additionally, this book is useful for
students planning to participate in programming competitions. After learning the
topics presented in this book, the learner will be capable of coding challenging
problems in Python.
1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.1 Why Python? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Non-library Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Enhancing Programming Skills and Creative Thinking
Through Challenging Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Prerequisite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.5 Target Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2 Python Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.1 How to Run a Python Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Data Types in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.2.1 Boolean Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.2 Integer Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.3 Decimal Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2.4 String Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.3 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.4 List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
2.4.1 List Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
2.4.2 List Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.5 Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
2.5.1 Sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.6 Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
2.6.1 Changing List Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
2.7 Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.7.1 Set Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.7.2 Set Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
2.8 Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
2.8.1 Nested Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
2.8.2 Dictionary Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . 48
2.8.3 Dictionary Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
vii
viii Contents
2.9 Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
2.9.1 Nested Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.9.2 Tuple Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.9.3 Tuple Constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
2.9.4 Range Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
2.10 Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
2.11 Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
2.12 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.12.1 For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
2.12.2 Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
2.13 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
2.13.1 Variable Scopes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
2.13.2 Lambda Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
2.13.3 Handling the Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . 70
2.14 Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
2.15 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
2.16 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3 Math .......................................................... 77
3.1 Josephus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.2 Reaching a Point in Lattice Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.3 Brussel Choice Problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.4 Inverse Collatz Conjecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.5 Counting Possible Corners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.6 Nearest S-gonal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.7 Finding Fulcrum Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
3.8 Counting Sphere Pyramid Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.9 Grouping Coins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.10 Median of Triple Medians . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.11 Smallest Seven-Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.12 Postfix Evaluate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3.13 Stable State in Bulgarian Solitaire . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
3.14 Computing the Rectangular Towers in Manhattan Skyline . . . . . . . 105
3.15 Cut Rectangular into Squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
3.16 Eliminating Corners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
3.17 Leibniz Triangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
3.18 Collatzy Distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
3.19 Sum of Two Squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
3.20 Has Three Summer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
3.21 Perfect Power . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
3.22 Lunar Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
3.23 n-th Term of Recaman Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
3.24 Van Eck Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
3.25 Non-consecutive Fibonacci Numbers . . . . . . . . . . . . . . . . . . . . . . . . . 133
3.26 Fibonacci Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Contents ix
xi
Chapter 1
Introduction
This chapter discusses the objectives, applications, and necessities of this book.
Most published Python books typically either cover the language’s syntax with basic
examples or focus on packages for problem-solving. However, using libraries and
simple exercises to understand Python’s structure can often be insufficient in provid-
ing developers with the necessary skills to tackle complex problems.
We believe that such approaches are inadequate for professional programmers who
are dealing with complex programs. Therefore, this book takes a different approach
by discussing problems that are not library-based (although standard libraries are
used in some programs), and presents solutions through detailed step-by-step algo-
rithms, hints, examples, and commented code. This approach is designed to equip
programmers with the necessary skills to solve more complex problems, leading to
an improvement in their overall programming abilities.
1.4 Prerequisite
This book presents and solves 90 challenges that can benefit a diverse range of people,
including computer science and engineering students, as well as anyone who wants
to master the Python language. The presented problems cover various fields, making
it suitable for a wide range of people. Moreover, this book enhances the power
of thinking and reasoning irrespective of the programming language. It can serve
as a valuable resource for teaching Python in universities or schools. Additionally,
software developers and participants in ACM or other competitions can benefit from
this book to improve their programming skills.
Chapter 2
Python Basics
This book uses Python version 3.9 and Windows 10 operating system. An integrated
development environment (IDE) is a programming environment that offers useful
features for programmers such as an editor, debugger, and code completion. The
use of an IDE simplifies Python coding. There are several popular IDEs available,
including Pycharm, Jupyter, and Spyder. The choice of IDE depends on personal
preference, as most IDEs use a Python interpreter, and their differences are mainly
in appearance and features. In this book, Spyder IDE is used for Python programming,
which requires the installation of Anaconda. Anaconda is an open-source distribution
that enables users of Windows, Linux, and other operating systems to code in Python
and R programming languages. The installation of Anaconda is a straightforward
process, like any other software, requiring only a few simple clicks. Figure 2.1 depicts
how the Anaconda must be installed. Once Anaconda is installed on Windows 10,
Spyder can be accessed by searching for ‘Spyder’ in the Windows search bar until
2
1
3 4
5
6
the Spyder icon is displayed. Clicking on the icon will open the Spyder environment,
as depicted in Fig. 2.2.
It is important to note that Spyder requires the installation of Anaconda, as men-
tioned earlier in the chapter.
Figure 2.3 depicts the Spyder environment that specifies the function of each
block, also, the F5 key can be used to run the written code.
2.1 How to Run a Python Program 7
In the real world, there are numerous objects that can exist in only two distinct states.
For example, an electronic device can be switched on or off, an individual can agree
or disagree with a particular stance, or a concept can have two opposing states. In
Python, the ‘True’ keyword signifies that the state is true, while the ‘False’ keyword
signifies that the state is false. In actuality, ‘True’ is equivalent to the numerical value
of 1, while ‘False’ is equivalent to 0.
In practice, integers are the most commonly used numeric type in real-life applica-
tions. They are widely used for counting odd and even numbers, tallying monetary
values, and similar tasks. For instance, the following code shows the addition of two
integer values:
1 x=2+3
2 print(x)
3 # Output: 5
There are several points to note regarding the code provided. Firstly, in line 1, a
variable named x is defined and assigned an integer value. Secondly, in line 2, the
print (x) statement is used to display the value stored within the variable x. Thirdly,
line 3 is a comment. In Python, comments are used to add annotations in the source
code for the purpose of improving its readability. Comments in Python are denoted
by the symbol #. It is worth noting that no explicit declaration for the variable x
is needed in Python. This is due to Python’s dynamic-typing feature, which allows
variables to be defined without specifying their type beforehand.
In the next some examples are provided in the below. Computing the remainder
of two numbers with notation % is performed, as follows:
1 x=2%3
2 print(x)
3 # Output: 2
Computing the multiplication of two numbers with notation ∗ is performed, as fol-
lows:
1 x=2*3
2 print(x)
3 # Output: 6
Computing the Division of two numbers with notation / is performed, as follows:
1 x=1/2
2 print(x)
3 # Output: 0.5
10 2 Python Basics
Computing the Division of two numbers with notation // is performed, where if the
result is decimal, their floor is taken, as follows:
1 x=1//2
2 print(x)
3 # Output: 0
Computing the power of two numbers with notation ∗∗ is performed, as follows:
1 x=2**3
2 print(x)
3 # Output: 8
Computing the minus of two numbers with notation − is performed, as follows:
1 x=2−3
2 print(x)
3 # Output: −1
In the next, the comparison operators on integers will be described. For the following
examples, the result is ‘True’ or ‘False’. For the variables of ‘a’ and ‘b’, a < b leads
to a true state if a is less than b, as follows:
1 a=4
2 b=8
3 z=a<b
4 print(z)
5 # Output: True
For the variables of ‘a’ and ‘b’, a > b leads to a true state if a is grater than b, as
follows:
1 a=4
2 b=8
3 z=a>b
4 print(z)
5 # Output: False
For the variables of ‘a’ and ‘b’, a <= b leads to a true state if a is less than or equal
to b, as follows:
1 a=4
2 b=8
3 z=b<=a
4 print(z)
5 # Output: False
For the variables of ‘a’ and ‘b’, a >= b leads to a true state if a is greater than or
equal to b, as follows:
1 a=4
2 b=8
2.2 Data Types in Python 11
3 z=b>=a
4 print(z)
5 # Output: True
For the variables of ‘a’ and ‘b’, a == b leads to a true state if a is equal to b, as
follows:
1 a=4
2 b=8
3 z=b=a
4 print(z)
5 # Output: False
For the variables of ‘a’ and ‘b’, a! = b leads to a true state if a is unequal to b, as
follows:
1 a=4
2 b=8
3 z=b!=a
4 print(z)
5 # Output: True
In the next, the logical operators on integers will be described. For the following
examples, the result is ‘True’ or ‘False’. For the variables of ‘a’ and ‘b’, a and b
leads to a true state if a and b true, as follows:
1 a=True
2 b=False
3 z= b and a
4 print(z)
5 # Output: False
1 a=True
2 b=True
3 z= b and a
4 print(z)
5 # Output: True
For the variables of ‘a’ and ‘b’, a or b leads to a true state if a or b is true, as follows:
1 a=True
2 b=False
3 z= b or a
4 print(z)
5 # Output: True
1 a=False
2 b=False
3 z= b or a
12 2 Python Basics
4 print(z)
5 # Output: False
For the variable of ‘a’, not (a) reverse the state ‘a’, as follows:
1 a=False
2 z= not(a)
3 print(z)
4 # Output: True
5 a=True
6 print(z)
7 # Output: False
In the above code, the value of variable a has changed once.
Decimal numbers are an important data type in Python, with a wide range of appli-
cations in everyday life. They are commonly used in scientific calculations, as well
as in calculations involving weights, lengths, times, and financial transactions. Dec-
imal numbers are particularly useful when precision is of utmost importance. For
instance, the multiplication of two decimal numbers in Python can be performed
using the operator ∗, as shown in the following code:
1 x=1.2*3.6
2 print(x)
3 # Output: 4.32
4 ################
5 x=0.2*4
6 print(x)
7 # Output: 0.8
Note
Note: All operators instructed for the integer numbers can be used for the
decimal numbers in Python.
In Python, strings are a fundamental data type used to represent text. They can
contain any character that Python supports and can be written using single quotes,
2.2 Data Types in Python 13
double quotes, or triple quotes. The use of single or double quotes is interchangeable,
with the only difference being that in a single-quoted string, double quotes can be
included and vice versa. Triple quotes, on the other hand, enable the creation of
strings spanning multiple lines. The following example shows how the strings in
Python are used.
1 x= ' Learning '
2 y= ' ' learning ' '
3 z= ' ' ' ' ' '
4 Learning
5 ''' '''
6 W= ' ' '
7 Learning
8 '''
In Python, an iterable object is any object that can be looped over using a loop
construct such as the for loop. In addition to strings, other iterable objects in Python
include lists, sets, tuples, dictionaries, and more.
Note
Note: Unlike strings, lists, sets, and other iterable objects, integer and decimal
types are not iterable in Python. If an attempt is made to loop over an integer
or decimal in Python, a TypeError will be raised by the Python interpreter.
String objects can be indexed, which means that individual characters within a
string can be accessed and manipulated using their position in the string. Indexing
is a common method for addressing elements within iterable objects in Python, and
is typically done using a numerical or string-based index. It is important to note
that in Python, the index of any object within an iterable is zero-based, meaning
that the first element has an index of 0, the second element has an index of 1, and
so on. The process of indexing in Python is demonstrated in Fig. 2.4. This figure
shows the string ‘university’ and its corresponding index positions highlighted in red
and orange. The red numbers represent direct indexing, where the position of each
character is indexed from left to right, starting at 0. The orange numbers represent
reverse indexing, where the position of each character is indexed from right to left,
starting at −1. In Python, for indexing objectname[n] is used, where objectname
is a variable that points to an iterable object, and n is a positive or negative integer or
14 2 Python Basics
a string. For a string object, n is a positive or negative integer. The following example
shows how the strings in Python are indexed.
1 x= ' University '
2 c=x[1]
3 print(c)
4 # output : n
5 c=x[−2]
6 print(c)
7 # t
8 '''
In addition to indexing notation, Python also provides a powerful method for address-
ing one or more elements within an iterable object, known as slicing. In Python, the
slicing notation is written as objectname[n1 : n2 : s], where objectname is a vari-
able that points to an iterable object, n1 and n2 are positive or negative integers
representing the start and end indices for slicing, and s indicates the interval between
the indices of the iterable object. The following example shows how the strings in
Python are sliced.
1 x= ' University '
2 c=x[1:3]
3 print(c)
4 # output : ni
5 c=x[2:7]
6 print(c)
7 # output : ivers
8 c=x[0:7]
9 print(c)
10 # output : Univers
11 c=x[:7]
12 print(c)
13 # output : Univers
14 c=x[4:]
15 print(c)
16 # output : ersity
17 ' ' ' ' ' 'The s t a r t and end addresses are not specified ,
18 so the whole string object is considered . ' ' ' ' ' '
19 c=x [ : : ]
20 print(c)
2.2 Data Types in Python 15
21 # output : University
22 c=x[ : : 2 ]
23 print(c)
24 # output : Uiest
25 # Reversing a string
26 c=x[::−1]
27 print(c)
28 # ytisrevinU
29 '''
In the above examples, it can be seen that if the start address is not specified,
slicing from the zero indexes is started, and if the end address is not specified, slicing
from the last index is done. Also, if the start and end addresses are not specified, the
whole string is considered. In the above examples, with x[:: 2] from the zero index
until the last index slicing is considered such that just the elements that are located in
the even indexes are selected. Additionally, to reverse a string in Python, the slicing
notation x[:: −1] can be used. This notation extracts the entire string starting from
the last index (−1) and moving towards the first index (0) with a step size of 1,
effectively reversing the order of the original string.
Note
Note: The indexing and slicing of all iterable objects in Python is the same.
In the next, the common operations in the strings can be applied with some exam-
ples being described. In all examples for the strings, stringobject is a variable that
points to a string object. For the variables of s1 and s2, notation + concat s1 and s2,
as follows:
1 s1= ' learning '
2 s2= ' data '
3 s3=s1+s2
4 print(s3)
5 # Output: learningdata
6 # defining a string that contains just a space
7 s0= ' ' ' ' ' ' ' ' ' ' ' '
8 s3=s1+s0+s2
9 print(s3)
10 # Output: learning data
16 2 Python Basics
The operator ∗ can be used to repeat a given string object multiple times. The syntax
for repeating a string is stringobject ∗ n, where stringobject is a variable that points
to a string object, and n is a positive integer indicating the number of times to repeat
the string. The following example illustrates how operator ∗ is used for the strings.
1 s1= ' learning '
2 s2=s1*3
3 # Output: learninglearninglearning
With \n, a new line in the string is generated, as follows:
1 s1= '#lea234rni ' 'ng\ nscience '
2 print(s1)
3 # Output: #lea234rning
4 science
In the above example, it can be seen that anything that Python encoding supports can
be written, and a new line is generated. With \t, a new tab in the string is generated,
as follows:
1 s1= '#lea234rni ' 'ng\ tscience '
2 print(s1)
3 # Output: #lea234rni ' 'ng science
Note
Note: A function is a block of code that performs a specific task and can
be called and executed multiple times throughout a program. Functions are a
fundamental concept in programming, allowing for the creation of modular,
reusable code that can be easily maintained and updated.
Note
Note: Built-in functions in Python are pre-defined functions that are part of the
Python language and can be executed just by referencing their name. These
functions are part of the Python Standard Library and provide a wide range of
functionality for common programming tasks, such as working with strings,
lists, and other data types.
2.2 Data Types in Python 17
Note
Note: An argument is any data that is passed to a function when it is called and
executed. This data can take many forms, such as integers, strings, lists, tuples,
dictionaries, or other objects. A parameter, on the other hand, is a variable
defined in the function that is used to receive and process the arguments passed
to the function. When calling a function in Python, one or more arguments can
be passed to the function as needed, and these arguments are then received by
the parameters of function and processed accordingly.
The string object has some built-in functions the most common ones with some
examples being described.
2.2.4.3 Count
Note
Note: If the start and end indexes are not specified, all indexes of an object are
considered.
18 2 Python Basics
2.2.4.4 Startswith
2.2.4.5 Endswith
2.2.4.6 Find
2.2.4.7 Index
Note
Note: The only difference between built-in functions of find and index is that
if the string is not found find returns −1 while index raises an error.
2.2.4.8 Encoding
Function of encoding takes two optional parameters encoding, and err or s, and
converts stringobject to an encoded sequence. Specifying the type of encod-
ing is with encoding parameter, and err or s determines if a character can not be
encoded, what should be replaced instead of the character. By default, the encod-
ing format is U T F − 8, but it can be changed to other formats. To use encode,
stringobject.encode() is used. The following example shows how encode func-
tion is used.
1 s= ' LearnScience '
2 c=s . encode()
3 print(c)
4 # b indicates i t is a byte string
5 #Output: b 'LearnScience '
6 # i f a character can not be encoded, i t will be ignored .
20 2 Python Basics
7 c=s . encode(encoding= ' ' ascii ' ' , errors= ' ' ignore ' ' )
8 print(c)
9 #Output: b 'LearnScience '
10 ' ' ' i f a character can not be encoded,
11 i t will raise a ValueError .
12 ' ' '
13 c=s . encode(encoding= ' ' ascii ' ' , errors= ' ' s t r i c t ' ' )
14 print(c)
15 #Output: b 'LearnScience '
2.2.4.9 Replace
This function replaces a given string with another string given. The r eplace takes two
string parameters of nw and pr , and optional parameter n, and stringobject.r epl-
cae( pr, nw, n), says how many times nw is replaced by pr that by default all string
that equal to pr are replaced. The following example shows how r eplace function
is used.
1 s= ' LearnScience '
2 c=s . replace ( 'n ' , ' * ' )
3 print(c)
4 #Output: Lear*Scie*ce
5 s= ' LearnScience '
6 c=s . replace ( 'n ' , ' * ' ,1)
7 print(c)
8 #Output: Lear*Science
Note
Note: The replace function doesn’t change the original string.
2.2.4.10 Strip
With stri p, any specified object is removed at the beginning or the end of string.
To use it, stringobject.stri p(char s) is used where char s is an optional parameter
that can be any string, by default, chars are space. The following example shows how
islower function is used.
1 s= ' ' ' as as as Univer sitY as s as as ' ' '
2 r=s . strip ( ' as ' )
3 print( r )
2.2 Data Types in Python 21
2.2.4.11 Join
With join, an arbitrary string object to each element of an iterable object (like string
and list) is added. To use it, stringobject. join(). The following example shows
how join function is used.
1 s1= ' learning '
2 s2= ' ** '
3 r=s2 . join (s1)
4 print( r )
5 #Output: l **e**a**r**n** i **n**g
6 s1= ' learning '
7 r= ' ' ' ' ' ' . join (s1)
8 print( r )
9 #Output: l e a r n i n g
10 s1= ' learning '
11 r= ' ' '$b ' ' ' . join (s1)
12 print( r )
13 #Output:l$be$ba$br$bn$bi$bn$bg
2.2.4.12 Split
With split, the string with a separator is splitted into a list. The stringobject.split-
(sep, m) is used to split, where sep and m are optional, and sep is a string that the
stringobject based on sep splitting is done, and m determines how many times the
split must be done. The following example shows how the split function is used. By
default, sep is a space and m is the maximum number of splitting.
1 s1= ' ' ' learning computer science ' ' '
2 r=s1 . s p l i t ()
3 print( r )
4 #Output:[ ' learning ' , 'computer ' , ' science ']
5 s1= ' ' ' learning computer science ' ' '
22 2 Python Basics
2.2.4.13 Capitalize
It capitali ze the first character (element) of a given string. The following example
shows how capitali ze function is used.
1 s= ' bulGarian '
2 r=s . capitalize ()
3 print( r )
4 #Output: BulGarian
5 s= ' Global '
6 r=s . capitalize ()
7 print( r )
8 #Output: Global
2.2.4.14 Swapcase
With swapcase, if the first character of a given string is a lower case, capitalize it,
and if the first character of a given string is a upper case, lower it. The following
example shows how swapcase function is used.
1 s= ' bulGarian '
2 r=s . swapcase()
3 print( r )
4 #Output: BulGarian
5 s= ' Global '
6 r=s . swapcase()
7 print( r )
8 #Output: global
2.2 Data Types in Python 23
2.2.4.15 Isalnum
With isalnum, if the characters of a given string are alphabet letters, numbers or
both, True is returned, else False is returned. The following example shows how
isalnum function is used.
1 s= ' bulGarian '
2 r=s . isalnum ()
3 print( r )
4 #Output: True
5 s= '#Global '
6 r=s . isalnum ()
7 print( r )
8 #Output: False
9 s= '#Global2023 '
10 r=s . isalnum ()
11 print( r )
12 #Output: True
2.2.4.16 Isnumeric
With isnumeric, if the characters of a given string are numeric, True is returned, else
False is returned. The following example shows how isnumeric function is used.
1 s= ' '
2 r=s . isnumeric ()
3 print( r )
4 s= '202220232024 '
5 r=s . isnumeric ()
6 print( r )
7 #Output: True
8 s= ' bulGarian '
9 r=s . isnumeric ()
10 print( r )
11 #Output: False
12 s= '#Global '
13 r=s . isnumeric ()
14 print( r )
15 #Output: False
16 s= '#Global2023 '
17 r=s . isnumeric ()
18 print( r )
19 #Output: False
24 2 Python Basics
2.2.4.17 Isalpha
With isalpha, if the characters of a given string are alphabet letters, True is returned,
else False is returned. The following example shows how isalpha function is used.
1 s= ' bulGarian '
2 r=s . isalpha ()
3 print( r )
4 #Output: True
5 s= '#Global '
6 r=s . isalpha ()
7 print( r )
8 #Output: False
9 s= '#Global2023 '
10 r=s . isalpha ()
11 print( r )
12 #Output: False
2.2.4.18 Islower
With islower , if the characters of a given string are in a lower case, True is returned,
else False is returned. The following example shows how islower function is used.
1 s= ' bulgarian '
2 r=s . islower ()
3 print( r )
4 #Output: True
5 s= '#global '
6 r=s . islower ()
7 print( r )
8 #Output: False
9 s= '#Global2023 '
10 r=s . islower ()
11 print( r )
12 #Output: False
2.2.4.19 Isupper
With isupper , if the characters of a given string are in an upper case, True is returned,
else False is returned. The following example shows how isupper function is used.
1 s= ' bulGarian '
2 r=s . isupper ()
2.2 Data Types in Python 25
3 print( r )
4 #Output: False
5 s= '#global '
6 r=s . isupper ()
7 print( r )
8 #Output: False
9 s= 'GLOBAL'
10 r=s . isupper ()
11 print( r )
12 #Output: True
2.2.4.20 Isspace
With isspace, if the characters of a given string are spaces, True is returned, else
False is returned. The following example shows how isspace function is used.
1 s= ' ' ' ' ' '
2 r=s . isspace ()
3 print( r )
4 #Output: True
5 s= '#global '
6 r=s . isspace ()
7 print( r )
8 #Output: False
9 s= 'world '
10 r=s . isspace ()
11 print( r )
12 #Output: False
2.2.4.21 Upper
With upper , the characters of a given string are changed to upper case. The following
example shows how upper function is used.
1 s= ' ' ' world ' ' '
2 r=s . upper ()
3 print( r )
4 #Output:WORLD
5 s= ' UniversitY '
6 r=s . upper ()
7 print( r )
8 #Output: UNIVERSITY
26 2 Python Basics
2.2.4.22 Lower
With lower , the characters of a given string are changed to lower case. The following
example shows how lower function is used.
1 s= ' ' 'worLD ' ' '
2 r=s . lower()
3 print( r )
4 #Output:world
5 s= ' UniversitY '
6 r=s . lower()
7 print( r )
8 #Output: university
9 s= 'PYTHON'
10 r=s . lower()
11 print( r )
12 #Output: python
The process of converting an object from one data type to another is known as type
conversion. Python provides built-in functions for converting between different data
types such that the type of an integer is represented by int, the decimal is represented
by f loat, and the string is represented by str . Also, the type name of any object in
Python with t ype(objectname) is taken. The following examples indicate how to
t ype function is used.
1 s= ' ' 'worLD ' ' '
2 r=type( s )
3 print( r )
4 #Output: <class ' str '>
5 s= '123 '
6 r=type( s )
7 print( r )
8 #Output:<class ' str '>
9 s=4
10 r=type( s )
11 print( r )
12 #Output: <class ' int '>
13 s=8.
14 r=type( s )
15 print( r )
16 #Output: <class ' float '>
17 s=2/4
2.2 Data Types in Python 27
18 r=type( s )
19 print( r )
20 #Output: <class ' float '>
To convert a value to another type, int (value), f loat (value), or str (value) is used,
where value is a specified object. Take a look at the following examples to see how
the conversion is made.
1 c0= ' 4.2 '
2 print(type(c0))
3 # Output: <class ' str '>
4 # Converting str to float type
5 c1=float (c0)
6 print(type(c1))
7 # Output: <class ' float '>
8 c0=4
9 print(type(c0))
10 # Output: <class ' int '>
11 # Converting int to float type
12 c1=float (c0)
13 print(type(c1))
14 # Output: <class ' float '>
15 c0=4.2
16 print(type(c0))
17 # Output: <class ' float '>
18 # Converting float to int type
19 c1=int (c0)
20 print(type(c1))
21 <class ' int '>
22 c0= 'Country '
23 '''
24 An error raises to convert
25 string l i t e r a l s to int or float
26 '''
27 c1=int (c0)
28 print(type(c1))
29 '''
30 Output: ValueError: invalid l i t e r a l
31 for int () with base 10: 'Country '
32 '''
33 c1=float (c0)
34 print(type(c1))
35 '''
36 Output: ValueError: could not
37 convert string to float : 'Country '
38 '''
28 2 Python Basics
39 c0=80
40 c1=81.9
41 c2=str (c0)
42 c3=str (c1)
43 print(type(c2))
44 print(type(c3))
45 # Output: <class ' str '>
46 # Output: <class ' str '>
Data is one of the most important entities in computer science. Data structures are
used to organize, store, and retrieve data efficiently. The choice of data structure
determines the format and organization of the stored data, and influences how the
data is stored in memory. In the following sections, we will describe some common
data structures in Python, including lists, arrays, matrices, sets, and dictionaries,
along with examples of how they can be used.
2.4 List
A linked list is a data structure where each element is linked to the next element, or
to the next and previous elements, and the elements in memory are not necessarily
stored consecutively. In Python, the list data structure is widely used and can be used
to implement other data structures such as matrices and arrays. Lists in Python are
used to store a sequence of elements, which can be of any data type supported by
Python. Lists have the following important features in Python:
1. Storing duplicate elements
There is no limit to store duplicate elements.
2. Storing heterogeneous elements Elements such as strings, integers, and strings
can be stored in a list.
3. Being sortable
A list can be sorted. For example, sort it from lower to upper, or alphabetically.
4. Being changeable
Lists are mutable data structures, which means that their content can be modified
after they are created. Once data is stored in a list, it can be changed as many
times as needed.
5. Being Iterable
A list is an iterable object that can be indexed.
In Python, lists are created using square brackets [], with the list elements separated
by commas inside the brackets. The following examples depict how the list is used.
2.4 List 29
The list object in Python provides a number of built-in functions for working with
lists, including functions for inserting, removing, counting, indexing, and more. Here
are some examples of how these functions can be used. In all examples, lst is a
variable that points to a list object, obj is any object, and iter obj is an iterable
object.
2.4.1.1 Append
With append, an object is inserted into the end of a list each time, To use it,
lst.append(obj) is used. The following examples indicate how to append func-
tion is used.
1 l s t =[2 ,3.1 , '− ' ]
2 l s t .append(77)
3 print( l s t )
4 # Output: [2,3.1, ' −' ,77]
5 lst0 =[101,102,9]
6 l s t .append( lst0 )
7 print( l s t )
8 # Output: [2 , 3.1,'−',77 [101, 102, 9]]
9 l s t .append(9.9)
10 print( l s t )
30 2 Python Basics
2.4.1.2 Extend
With extend, an iterable object is inserted into the end of a list each time. To use
it, lst.extend(iter obj) is used. With this definition, int object and float do not work
with extend function. As a solution, float and int objects must be converted to type
string and then they can work the extend function. The following examples indicate
how to extend function is used.
1 s= ' ' learning ' '
2 l s t =[]
3 l s t . extend( s )
4 # Output: [ ' l ' , ' e ' , 'a ' , ' r ' , 'n ' , ' i ' , 'n ' , 'g ']
5 s= ' ' learning ' '
In python, if a string is inserted with extend function, each character is inserted into
an index. To insert a string into an index of a list with the extend function, the string
must split as follows:
1 s= ' ' learning ' '
2 l s t =[]
3 l s t . extend( s . s p l i t ( ) )
4 # Output: [ ' ' learning ' ']
Other example are as follows:
1 lst0=[ ' theta ' ]
2 l s t =[]
3 r= ' learning '
4 l s t . extend( lst0 )
5 l s t . extend( r )
6 print( l s t )
7 # Output: [ ' theta ' , ' l ' , 'e ' , 'a ' , ' r ' , 'n ' , ' i ' , 'n ' , 'g ']
The extend() function in Python is used to add elements from an iterable object to
the end of a list. However, if a non-iterable object such as an integer or float is passed
to the extend() function, Python will raise a TypeError because the object cannot be
iterated over.
1 l s t =[]
2 l s t . extend(9)
3 # Output: TypeError: ' int ' object is not iterable
4 l s t =[]
5 l s t . extend(9.87)
6 # Output: TypeError: ' float ' object is not iterable
2.4 List 31
In the above examples, Python raises the errors, because int and float are not iterable.
Take a look at the following other examples.
1 l s t =[]
2 l s t . extend ([9])
3 # Output: [9]
4 l s t .append([9])
5 # Output: [[9]]
2.4.1.3 Insert
If an object must be inserted into a specific position, the insert function must be
used. To use it, lst.insert (ind, obj) is used, where ind is an integer that specifies
the index that the object must be inserted. The following examples indicate how to
insert function is used.
1 l s t =[1,8,9, '8 ' ,7 ,6]
2 l s t . insert(−2, ' objj ' )
3 print( l s t )
4 # Output: [1 , 8, 9, '8 ' , ' objj ' , 7, 6]
5 l s t =[1,8,9, '8 ' ,7 ,6]
6 l s t . insert (1 , ' data ' )
7 print( l s t )
8 # Output: [1 , ' data ' , 8, 9, '8 ' , ' objj ' , 7, 6]
9 l s t . insert (4 ,7)
10 print( l s t )
11 # Output: [1 , ' data ' , 8, 9, 7, '8 ' , ' objj ' , 7, 6]
As another example, consider Code 2.1. When inserting an object in position or index
zero, the new object is inserted in the index of zero and the old object is inserted in
the index or position one.
Code 2.1 Python code to insert the objects into a list in a reverse order
1 current_sublist =[]
2 current_sublist . insert (0 ,5)
3 current_sublist . insert (0 ,7)
4 current_sublist . insert (0,220)
5 '''
6 The output is:
7
8 [220, 7, 5]
9 '''
If an object is to be inserted at the same index, the previous object should be shifted
one position after the current one.
32 2 Python Basics
Note
Note: append, extend, and insert are used to put data into a list, where the
append and extend functions put the data to the end of a list each time, and
append works with objects, while extend works with iterable objects. The
insert function is used to put an object into a specified index.
2.4.1.4 Count
2.4.1.5 Index
Function of index takes three parameters obj, s and e, if lst find gobj, returns its
index in lst and else raises a ValueError, The format to use it, is lst.index(obj, s, e),
where s is the start address, and e is the end address to find the index. The following
example shows how index function is used.
1 l s t =[1, ' data ' , 8, 9, 7, 8, 7, 6]
2 c=l s t . index(8)
3 print(c)
4 # Output: 2
5 c=l s t . index(8 ,3 ,6)
6 print(c)
7 # Output: 5
2.4.1.6 Clear
To clear all content of the list object, clear function is used. No argument is sent to
clear function. The following example indicates how clear function can be used.
2.4 List 33
2.4.1.7 Remove
To remove a specific object, r emove function is used. To use it, lst.r emove(obj) is
used. If the object is not in lst, an error is raised. The following examples indicate
how r emove function is used.
1 l s t =[1, ' data ' , 8, 9, 7, '8 ' , 7, 6]
2 l s t .remove(8)
3 print( l s t )
4 # Output: [1 , ' data ' , 8, 9, 7, '8 ' , 7]
5 l s t .remove(76)
6 print( l s t )
7 # Output: ValueError: l i s t .remove(x ): x not in l i s t
2.4.1.8 Pop
To remove a specific object, pop function is used. To use it, lst. pop(ind) is used,
where ind is an optional parameter that specifies the index object is to be removed.
The default value for pop is equal to the index of the last item, and if the entered
index is not in the range index of lst, an error is raised. The following examples
indicate how pop function is used.
1 l s t =[1, ' data ' , 8, 9, 7, '8 ' , 7, 6]
2 l s t .pop(8)
3 # Output: IndexError: pop index out of range
4 l s t =[1, ' data ' , 8, 9, 7, '8 ' , 7, 6]
5 l s t .pop(3)
6 print( l s t )
7 # Output: [1 , ' data ' , 8, 7, '8 ' , 7, 6]
34 2 Python Basics
Note
Note: remove and pop are used to delete objects into a list, where remove
deletes an object by its object and pop deletes an object by its index. The
clear() function is a built-in method of the list object that is used to remove all
elements from a list, leaving it empty.
2.4.1.9 Reverse
2.4.1.10 Copy
A nested list is a list of lists; or a list/lists are into another list. The following example
creates a nested list.
1 nlst=[
2 [5.69 ,8 ,4.6] ,
3 [ 'x ' , ' a ' ,0.88] ,
4 [66, 7.7 , '8 ' ]]
All built-in functions can be applied to the nested lists. Take a look at the following
example.
1 nlst=[
2 [5.69 ,8 ,4.6] ,
3 [ 'x ' , ' a ' ,0.88] ,
4 [66, 7.7 , '8 ' ]]
5 # ind=nlst . index([66 , 7.7 , '8 '])
6 # Output: 2
In a nested list, all lists that are in other lists, have their indexes. The more nested,
the more indices must be used to access the elements of a nested list. Take a look at
the following examples.
1 nlst=[
2 [5 ,8 ,4] ,
3 [ 'x ' , ' a ' ,0.88 , ' r ' ] ,
4 [66, 7.7 ,[10 ,9 ,8] ,4] ]
5 # To access the f i s t l i s t and i t s second element
6 val=nlst [1]
7 print( val )
8 # Output: [ 'x ' , 'a ' ,0.88 , ' r ']
9 val=nlst [0][1]
10 print( val )
11 # Output: 8
12 val=nlst [2][3]
13 print( val )
14 # Output: [10, 9, 8]
15 val=nlst [2][2][1]
16 print( val )
17 # Output: 9
36 2 Python Basics
In the above examples, it can be seen that to access a nested list more than an index
must be used. With details, to access element 9 located in [66, 7.7, [10, 9, 8], 4], in
the above nested list, [2][2][1] is used, where [2] points to [66, 7.7, [10, 9, 8], 4],
[2][2] points to [10, 9, 8], and [2][2][1] points to 9.
Function of list () as input takes an optional iterable object, and converts it to a list
object, to use it, list (iter obj) is used. In a simple statement, each element of iter obj
is placed in an index of the list. Take a look at the following examples. All built-in
functions for the list that is created with [] can be applied to the list constructor.
1 l s t=l i s t ( ' learning ' )
2 print( l s t )
3 # Output: [ ' l ' , 'e ' , 'a ' , ' r ' , 'n ' , ' i ' , 'n ' , 'g ']
4 l s t=l i s t ( '1234 ' )
5 print( l s t )
6 # Output: [ '1 ' , '2 ' , '3 ' , '4 ']
2.5 Array
An array consists of data of the same type, whose elements can be accessed using its
indices. The elements in an array are stored sequentially in memory as opposed to a
list, which means that accessing the elements in the array is faster. In Python, there
is no special command to use an array, but a list is used. In other words, as the data
in the array must be of the same type, then only the data of the same type is used in
the list. In this regard, all built-in functions for the list can be applied to the arrays.
Take a look at the following examples.
1 # Creating an array of integers with the size of 6
2 arr =[1 ,4 ,5 ,7 ,9]
3 # Accessing to an element
4 print( arr =[0])
5 # Output: 1
6 # Creating an array of strings with the size of 6
7 arr=[ 'v ' , ' c ' , 'g ' , 'n ' ]
8 d=arr[0]+arr [2]
9 print(d)
10 # Output: vg
2.6 Matrix 37
2.5.1 Sort
Sort is a built-in function of the list, but sort can be applied to data of the same
type, so it applies to an array. With sor t (r ever se, key) function, the elements in
ascending or descending order are sorted. In the sort function, r ever se and key are
optional parameters such that r ever se is a binary value, and if it is False, sorts in
ascending order, else (T r ue) sorts in descending order, by default r ever se is equal to
False. The parameter of key determines the sorting criteria. The following examples
indicate how sor t function is used.
1 arr =[3,86,5,7,2,9]
2 # Sorting in ascending order
3 arr . sort ()
4 print( arr )
5 # Output: [2 , 3, 5, 7, 9, 86]
6 arr . sort ( reverse=True)
7 print( arr )
8 # Output: [86, 9, 7, 5, 3, 2]
9 arr=arr . sort ( reverse=True)
10 print( arr )
11 # Output: None
If the sorting is assigned to a variable, N one is returned, where N one means no
value and has the type of N oneT ype.
2.6 Matrix
8 88,4,32,41, respectively .
9 The third row: [66, 3 ,19 ,4] , for the third row,
10 column 0, 1,2 and 3 are
11 66, 3,19,4, respectively .
12 ' ' ' ' ' '
13 mat=[
14 [5 ,8 ,4 ,6] ,
15 [88,4,32,41] ,
16 [66, 3,19,4] ]
2.7 Set
A set object is a built-in data structure in Python that represents a collection of unique
elements. Similar to a list or tuple, a set can contain elements of different data types,
and the elements are not stored in any particular order. Some key features of sets in
Python include:
1. Non-indexable
In contrast to a list object, the set object can not be addressed by an index.
2. Unchangeable
Elements of a set can be added or removed, but not changed by another value.
3. A set cannot have duplicate elements. Sets are used for math, from a practical
point of view, sets are used to perform mathematical operations, and remove
duplicate elements. To create a set in Python, an open curly bracket ‘{’ and a
closed curly bracket ‘}’ are used with initializing value to it, or a set () is used.
The following examples indicate how a set object is used. In all examples, se is a set
object, and iter obj is an iterable object.
1 se={3,4,7,6,0,9,3,7}
2 print( se )
3 # Output: {0, 3, 4, 6, 7, 9}
4 se={7,6, ' learn ' , ' a ' , 'b ' , ' a '}
5 print( se )
6 # Output: { ' learn ' , 6, 7, 'b ' , 'a '}
Notice that with {}, a dictionary is created not a set.
Set object in Python has some built-in functions that are to be described in the next.
2.7.1.1 Add
With add function, an element to a set is added, To use it, se.add(elem) is used,
where elem can not be a list object or set object. The following examples indicate
how add function in a set is used.
1 se={3,4,7,6,0,9,3,7}
2 se .add(21)
3 # Output: {0, 3, 4, 21, 6, 7, 9}
4 se .add(43.4)
5 print( se )
6 # Output: {0, 3, 4, 21, 6, 7, 9, 43.4}
40 2 Python Basics
2.7.1.2 Update
To include a list or a set se.update(iter obj) is used. The following examples indicate
how update function in a set is used.
1 se={0, 3, 4, 21, 6, 7, 9}
2 s1={79, 'you '}
3 se . update(s1)
4 print( se )
5 # Output: {0, 3, 4, 6, 7, 9, 79, 21, 'you '}
6 l s t =[ 'nba ' ,40 , '79 ' ]
7 se . update( l s t )
8 print( se )
9 '''
10 Output: {0, 3, 4, 6, 7, 'nba ' , 9, 40, '79 ' , 79, 21, 'you '}
11 ' ' '
2.7.1.3 Clear
To clear a set clear , se.clear () is used. No argument is sent to clear function. The
following example indicates how clear function in a set can be used.
1 se={0, 3, 4, 21, 6, 7, 9}
2 se . clear ()
3 print( se )
4 # Output: set ()
2.7.1.4 Union
With union, the union of a set with an iterable object is taken, To use it, se.union
(iter obj) is used. The following examples indicate how union function in a set is
used.
Random documents with unrelated
content Scribd suggests to you:
irrelevantly; “but my family have just written me that they won’t
stand for it. So I suppose I’ll have to go into tenement work here in
the city instead.” With a visible effort she jerked her mind back again
to the feverish question in Rae Malgregor’s eyes. “Oh, you want to
know where I got my motto?” she asked. A flash of intuition
brightened suddenly across her absent-mindedness. “Oh,” she
smiled, “you mean you want to know just what the incident was that
first made me decide to devote my life to humanity?”
“Yes,” snapped Rae Malgregor.
A little shyly Helene Churchill picked up her copy of Marcus
Aurelius and cuddled her cheek against its tender morocco cover.
“Really?” she questioned with palpable hesitation—“really, you
want to know? Why, why—it’s rather a—sacred little story to me. I
shouldn’t exactly want to have anybody—laugh about it.”
“I’ll laugh if I want to,” attested Zillah Forsyth, forcibly, from the
other side of the room.
Like a pugnacious boy’s, Rae Malgregor’s fluent fingers doubled
up into two firm fists.
“I’ll punch her if she even looks as though she wanted to,” she
signaled surreptitiously to Helene.
Shrewdly for an instant the city girl’s narrowing eyes challenged
and appraised the country girl’s desperate sincerity. Then quite
abruptly she began her little story.
“Why, it was on an Easter Sunday, oh, ages and ages ago,” she
faltered. “Why, I couldn’t have been more than nine years old at the
time.” A trifle self-consciously she turned her face away from Zillah
Forsyth’s supercilious smile. “And I was coming home from a
Sunday-school festival in my best white muslin dress, with a big pot
of purple pansies in my hand,” she hastened somewhat nervously to
explain. “And just at the edge of the gutter there was a dreadful
drunken man lying in the mud, with a great crowd of cruel people
teasing and tormenting him. And because—because I couldn’t think
of anything else to do about it, I—I walked right up to the poor old
creature, scared as I could be, and—and I presented him with my
pot of purple pansies. And everybody of course began to laugh—to
scream, I mean—and shout with amusement. And I, of course,
began to cry. And the old drunken man straightened up very oddly
for an instant, with his battered hat in one hand and the pot of
pansies in the other, and he raised the pot of pansies very high, as
though it had been a glass of rarest wine, and bowed to me as
reverently as though he had been toasting me at my father’s table at
some very grand dinner. And ‘Inasmuch,’ he said. Just that
—‘Inasmuch.’ So that’s how I happened to go into nursing,” she
finished as abruptly as she had begun. Like some wonderful
phosphorescent manifestation her whole shining soul seemed to
flare forth suddenly through her plain face.
With honest perplexity Zillah Forsyth looked up from her work.
“So that’s how you happened to go into nursing?” she quizzed
impatiently. Her long straight nose was all puckered tight with
interrogation. Her dove-like eyes were fairly dilated with slow-
dawning astonishment. “You—don’t—mean,” she gasped—“you don’t
mean that just for that?” Incredulously she jumped to her feet and
stood staring blankly into the city girl’s strangely illuminated
features. “Well, if I were a swell like you,” she scoffed, “it would take
a heap sight more than a drunken man munching pansies and rum
and Bible texts to—to jolt me out of my limousines and steam-yachts
and Adirondack bungalows.”
Quite against all intention, Helene Churchill laughed. She did not
often laugh. Just for an instant her eyes and Zillah Forsyth’s clashed
together in the irremediable antagonism of caste, the plebeian’s
scornful impatience with the aristocrat equaled only by the
aristocrat’s condescending patience with the plebeian.
It was no more than right that the aristocrat should recover her
self-possession first.
“Never mind about your understanding, Zillah dear,” she said
softly. “Your hair is the most beautiful thing I ever saw in my life.”
Along Zillah Forsyth’s ivory cheek an incongruous little flush of
red began to show. With much more nonchalance than was really
necessary she pointed toward her half-packed trunk.
“It wasn’t Sunday-school I was coming home from when I got my
motto,” she remarked dryly, with a wink at no one in particular. “And,
so far as I know,” she proceeded with increasing sarcasm, “the man
who inspired my noble life was not in any way particularly addicted
to the use of alcoholic beverages.” As though her collar was
suddenly too tight, she rammed her finger down between her stiff
white neck-band and her soft white throat. “He was a New York
doctor,” she hastened somewhat airily to explain. “Gee! but he was a
swell! And he was spending his summer holidays up in the same
Maine town where I was tending soda-fountain. And he used to drop
into the drug store nights after cigars and things. And he used to tell
me stories about the drugs and things, sitting up there on the
counter, swinging his legs and pointing out this and that—quinine,
ipecac, opium, hashish—all the silly patent medicines, every sloppy
soothing-syrup! Lordy! he knew ’em as though they were people—
where they come from, where they’re going to, yarns about the
tropics that would kink the hair along the nape of your neck, jokes
about your own town’s soup-kettle pharmacology that would make
you yell for joy. Gee! but the things that man had seen and known!
Gee! but the things that man could make you see and know! And he
had an automobile,” she confided proudly. “It was one of those
billion-dollar French cars, and I lived just round the corner from the
drug store; but we used to ride home by way of—New Hampshire.”
Almost imperceptibly her breath began to quicken.
“Gee! those nights!” she muttered. “Rain or shine, moon or
thunder, tearing down those country roads at forty miles an hour,
singing, hollering, whispering! It was him that taught me to do my
hair like this instead of all the cheap rats and pompadours every
other kid in town was wearing,” she asserted quite irrelevantly; then
stopped with a furtive glance of suspicion toward both her listeners
and mouthed her way delicately back to the beginning of her
sentence again. “It was he that taught me to do my hair like this,”
she repeated, with the faintest possible suggestion of hauteur.
For one reason or another along the exquisitely chaste curve of
her cheek a narrow streak of red began to show again.
“And he went away very sudden at the last,” she finished
hurriedly. “It seems he was married all the time.” Blandly she turned
her wonderful face to the caressing light. “And—I hope he goes to
hell,” she added.
With a little gasp of astonishment, shock, suspicion, distaste,
Helene Churchill reached out an immediate conscientious hand to
her.
“O Zillah,” she began, “O poor Zillah dear! I’m so sorry! I’m so—”
Absolutely serenely, through a mask of insolence and ice, Zillah
Forsyth ignored the proffered hand.
“I don’t know what particular call you’ve got to be sorry for me,
Helene Churchill,” she drawled languidly. “I’ve got my character,
same as you’ve got yours, and just about nine times as many good
looks. And when it comes to nursing—” Like an alto song pierced
suddenly by one shrill treble note, the girl’s immobile face sharpened
transiently with a single jagged flash of emotion. “And when it
comes to nursing? Ha! Helene Churchill, you can lead your class all
you want to with your silk-lined manners and your fuddy-duddy
book-talk; but when genteel people like you are moping round all
ready to fold your patients’ hands on their breasts and murmur, ‘Thy
will be done,’ why, that’s the time that little ‘Yours Truly’ is just
beginning to roll up her sleeves and get to work.”
With real passion her slender fingers went clutching again at her
harsh linen collar. “It isn’t you, Helene Churchill,” she taunted, “that’s
ever been to the Superintendent on your bended knees and begged
for the rabies cases and the small-pox! Gee! you like nursing
because you think it’s pious to like it; but I like it because I like it!”
From brow to chin, as though fairly stricken with sincerity, her whole
bland face furrowed startlingly with crude expressiveness. “The smell
of ether,” she stammered, “it’s like wine to me. The clang of the
ambulance gong? I’d rather hear it than fire-engines. I’d crawl on
my hands and knees a hundred miles to watch a major operation. I
wish there was a war. I’d give my life to see a cholera epidemic.”
As abruptly as it came, the passion faded from her face, leaving
every feature tranquil again, demure, exaggeratedly innocent. With
saccharine sweetness she turned to Rae Malgregor.
“Now, little one,” she mocked, “tell us the story of your lovely life.
Having heard me coyly confess that I went into nursing because I
had such a crush on this world, and Helene here brazenly affirm that
she went into nursing because she had such a crush on the world to
come, it’s up to you now to confide to us just how you happened to
take up so noble an endeavor. Had you seen some of the young
house doctors’ beautiful, smiling faces depicted in the hospital
catalogue? Or was it for the sake of the Senior Surgeon’s grim, gray
mug that you jilted your poor plowboy lover way up in the Annapolis
Valley?”
“Why, Zillah,” gasped the country girl—“why, I think you’re
perfectly awful! Why, Zillah Forsyth! Don’t you ever say a thing like
that again! You can joke all you want to about the flirty young
internes,—they’re nothing but fellows,—but it isn’t—it isn’t respectful
for you to talk like that about the Senior Surgeon. He’s too—too
terrifying,” she finished in an utter panic of consternation.
“Oh, now I know it was the Senior Surgeon that made you jilt
your country beau,” taunted Zillah Forsyth, with soft alto sarcasm.
“I didn’t, either, jilt Joe Hazeltine,” stormed Rae Malgregor,
explosively. Backed up against her bureau, eyes flaming, breast
heaving, little candy-box cap all tossed askew over her left ear, she
stood defying her tormentor. “I didn’t, either, jilt Joe Hazeltine,” she
reasserted passionately. “It was Joe Hazeltine that jilted me; and
we’d been going together since we were kids! And now he’s married
the dominie’s daughter, and they’ve got a kid of their own ’most as
old as he and I were when we first began courting each other. And
it’s all because I insisted on being a trained nurse,” she finished
shrilly.
With an expression of real shock, Helene Churchill peered up
from her lowly seat on the floor.
“You mean,” she asked a bit breathlessly—“you mean that he
didn’t want you to be a trained nurse? You mean that he wasn’t big
enough, wasn’t fine enough, to appreciate the nobility of the
profession?”
“Nobility nothing!” snapped Rae Malgregor. “It was me scrubbing
strange men with alcohol that he couldn’t stand for, and I don’t
know as I exactly blame him,” she added huskily. “It certainly is a
good deal of a liberty when you stop to think about it.”
Quite incongruously her big childish blue eyes narrowed suddenly
into two dark, calculating slits.
“It’s comic,” she mused, “how there isn’t a man in the world who
would stand letting his wife or daughter or sister have a male nurse;
but look at the jobs we girls get sent out on! It’s very confusing.”
With sincere appeal she turned to Zillah Forsyth. “And yet—and yet,”
she stammered, “and yet when everything scary that’s in you has
once been scared out of you, why, there’s nothing left in you to be
scared with any more, is there?”
“What? What?” pleaded Helene Churchill. “Say it again! What?”
“That’s what Joe and I quarreled about, my first vacation home,”
persisted Rae Malgregor. “It was a traveling salesman’s thigh. It was
broken bad. Somebody had to take care of it; so I did. Joe thought it
wasn’t modest to be so willing.” With a perplexed sort of defiance
she raised her square little chin. “But, you see, I was willing,” she
said. “I was perfectly willing. Just one single solitary year of hospital
training had made me perfectly willing. And you can’t un-willing a
willing even to please your beau, no matter how hard you try.” With
a droll admixture of shyness and disdain, she tossed her curly blond
head a trifle higher. “Shucks!” she attested, “what’s a traveling
salesman’s thigh?”
“Shucks yourself!” scoffed Zillah Forsyth. “What’s a silly beau or
two up in Nova Scotia to a girl with looks like you? You could have
married that typhoid case a dozen times last winter if you’d crooked
your little finger. Why, the fellow was crazy about you. And he was
richer than Crœsus. What queered it?” she demanded bluntly. “Did
his mother hate you?”
Like one fairly cramped with astonishment, Rae Malgregor
doubled up very suddenly at the waist-line, and, thrusting her neck
oddly forward after the manner of a startled crane, stood peering
sharply round the corner of the rocking-chair at Zillah Forsyth.
“Did his mother hate me?” she gasped. “Did—his—mother—hate
me? Well, what do you think? With me, who never even saw
plumbing till I came down here, setting out to explain to her, with
twenty tiled bath-rooms, how to be hygienic though rich? Did his
mother hate me? Well, what do you think? With her who bore him—
her who bore him, mind you—kept waiting down-stairs in the
hospital anteroom half an hour every day on the raw edge of a
rattan chair, waiting, worrying, all old and gray and scared, while
little, young, perky, pink-and-white me is up-stairs brushing her own
son’s hair and washing her own son’s face and altogether getting her
own son ready to see his own mother! And then me obliged to turn
her out again in ten minutes, flip as you please, ‘for fear she’d
stayed too long,’ while I stay on the rest of the night? Did his mother
hate me?”
As stealthily as an assassin she crept around the corner of the
rocking-chair and grabbed Zillah Forsyth by her astonished linen
shoulder.
“Did his mother hate me?” she persisted mockingly. “Did his
mother hate me? My God! Is there any woman from here to
Kamchatka who doesn’t hate us? Is there any woman from here to
Kamchatka who doesn’t look upon a trained nurse as her natural-
born enemy? I don’t blame ’em,” she added chokingly. “Look at the
impudent jobs we get sent out on! Quarantined up-stairs for weeks
at a time with their inflammable, diphtheretic bridegrooms while
they sit down-stairs brooding over their wedding teaspoons! Hiked
off indefinitely to Atlantic City with their gouty bachelor uncles!
Hearing their own innocent little sister’s blood-curdling death-bed
deliriums! Snatching their own new-born babies away from their
breasts and showing them, virgin-handed, how to nurse them
better! The impudence of it, I say, the disgusting, confounded
impudence—doing things perfectly, flippantly, right, for twenty-one
dollars a week—and washing—that all the achin’ love in the world
don’t know how to do right just for love!” Furiously she began to jerk
her victim’s shoulder. “I tell you it’s awful, Zillah Forsyth,” she
insisted. “I tell you I just won’t stand it!”
With muscles like steel wire, Zillah Forsyth scrambled to her feet,
and pushed Rae Malgregor back against the bureau.
“For Heaven’s sake, Rae, shut up!” she said. “What in creation’s
the matter with you to-day? I never saw you act so before.” With
real concern she stared into the girl’s turbid eyes. “If you feel like
that about it, what in thunder did you go into nursing for?” she
demanded not unkindly.
Very slowly Helene Churchill rose from her lowly seat by her
precious book-case and came round and looked at Rae Malgregor
rather oddly.
“Yes,” she faltered, “what did you go into nursing for?” The
faintest possible taint of asperity was in her voice.
Quite dumbly for an instant Rae Malgregor’s natural timidity
stood battling the almost fanatic professional fervor in Helene
Churchill’s frankly open face, the raw scientific passion, of very
different caliber, but of no less intensity, hidden craftily behind Zillah
Forsyth’s plastic features; then suddenly her own hands went
clutching back at the bureau for support, and all the flaming, raging
red went ebbing out of her cheeks, leaving her lips with hardly blood
enough left to work them.
“I went into nursing,” she mumbled, “and it’s God’s own truth—I
went into nursing because—because I thought the uniforms were so
cute.”
Furiously, the instant the words were gone from her mouth, she
turned and snarled at Zillah’s hooting laughter.
“Well, I had to do something,” she attested. The defense was like
a flat blade slapping the air.
Desperately she turned to Helene Churchill’s goading, faintly
supercilious smile, and her voice edged suddenly like a twisted
sword.
“Well, the uniforms are cute,” she parried. “They are! They are! I
bet you there’s more than one girl standing high in the graduating
class to-day who never would have stuck out her first year’s bossin’
and slops and worry and death if she’d had to stick it out in the
unimportant-looking clothes she came from home in. Even you,
Helene Churchill, with all your pious talk, the day they put your
coachman’s son in as new interne and you got called down from the
office for failing to stand when Mr. Young Coachman came into the
room, you bawled all night. You did, you did, and swore you’d chuck
your whole job and go home the next day if it wasn’t that you’d just
had a life-size photo taken in full nursing costume to send to your
brother’s chum at Vale! So there!”
With a gasp of ineffable satisfaction she turned from Helene
Churchill.
“Sure the uniforms are cute,” she slashed back at Zillah Forsyth.
“That’s the whole trouble with ’em. They’re so awfully,
masqueradishly cute! Sure I could have gotten engaged to the
typhoid boy. It would have been as easy as robbing a babe. But lots
of girls, I notice, get engaged in their uniforms, feeding a patient
perfectly scientifically out of his own silver spoon, who don’t seem to
stay engaged so specially long in their own street clothes, bungling
just plain naturally with their own knives and forks. Even you, Zillah
Forsyth,” she hacked—“even you, who trot round like the ‘Lord’s
anointed’ in your pure white togs, you’re just as Dutchy-looking as
anybody else come to put you in a red hat and a tan coat and a blue
skirt.”
Mechanically she raised her hands to her head as though with
some silly thought of keeping the horrid pain in her temples from
slipping to her throat, her breast, her feet.
“Sure the uniforms are cute,” she persisted a bit thickly. “Sure the
typhoid boy was crazy about me. He called me his ‘holy chorus girl.’ I
heard him raving in his sleep. Lord save us! What are we to any man
but just that?” she questioned hotly, with renewed venom. “Parson,
actor, young sinner, old saint—I ask you frankly, girls, on your word
of honor, was there ever more than one man in ten went through
your hands who didn’t turn out soft somewhere before you were
through with him? Mawking about your ‘sweet eyes’ while you’re
wrecking your optic nerves trying to decipher the dose on a poison
bottle! Mooning over your wonderful likeness to the lovely young
sister they never had! Trying to kiss your finger-tips when you’re
struggling to brush their teeth! Teasin’ you to smoke cigarettes with
’em when they know it would cost you your job!”
Impishly, without any warning, she crooked her knee and pointed
one homely, square-toed shoe in a mincing dancing step.
Hoidenishly she threw out her arms and tried to gather Helene and
Zillah both into their compass.
“Oh, you holy chorus girls!” she chuckled, with maniacal delight.
“Everybody all together, now! Kick your little kicks! Smile your little
smiles! Tinkle your little thermometers! Steady, there! One, two,
three! One, two, three!”
Laughingly, Zillah Forsyth slipped from the grasp.
“Don’t you dare ‘holy’ me!” she cried.
In real irritation Helene released herself.
“I’m no chorus girl,” she said coldly.
With a shrill little scream of pain, Rae Malgregor’s hands went
flying back to her temples. Like a person giving orders in a great
panic, she turned authoritatively to her two room-mates, her fingers
all the while boring frenziedly into her temples.
“Now, girls,” she warned, “stand well back! If my head bursts,
you know, it’s going to burst all slivers and splinters, like a boiler.”
“Rae, you’re crazy,” hooted Zillah.
“Just plain vulgar—loony,” faltered Helene.
Both girls reached out simultaneously to push her aside.
Somewhere in the dusty, indifferent street a bird’s note rang out
in one wild, delirious ecstasy of untrammeled springtime. To all
intents and purposes the sound might have been the one final signal
that Rae Malgregor’s jangled nerves were waiting for.
“Oh, I am crazy, am I?” she cried, with a new, fierce joy. “Oh, I
am crazy, am I? Well, I’ll go ask the Superintendent and see if I am.
Oh, surely they wouldn’t try and make me graduate if I really was
crazy!”
Madly she bolted for her bureau, and, snatching her own motto
down, crumpled its face securely against her skirt, and started for
the door. Just what the motto was no one but herself knew.
Sprawling in paint-brush hieroglyphics on a great flapping sheet of
brown wrapping-paper, the sentiment, whatever it was, had been
nailed face down to the wall for three tantalizing years.
“No, you don’t!” Zillah cried now, as she saw the mystery
threatening meanly to escape her.
“No, you don’t!” cried Helene. “You’ve seen our mottos, and now
we’re going to see yours!”
Almost crazed with new terror, Rae Malgregor went dodging to
the right, to the left, to the right again, cleared the rocking-chair, a
scuffle with padded hands, climbed the trunk, a race with padded
feet, reached the door-handle at last, yanked the door open, and
with lungs and temper fairly bursting with momentum, shot down
the hall, down some stairs, down some more hall, down some more
stairs to the Superintendent’s office, where, with her precious motto
still clutched securely in one hand, she broke upon that dignitary’s
startled, near-sighted vision like a young whirlwind of linen and
starch and flapping brown paper. Breathlessly, without prelude or
preamble, she hurled her grievance into the older woman’s
grievance-dulled ears.
“Give me back my own face!” she demanded peremptorily. “Give
me back my own face, I say! And my own hands! I tell you, I want
my own hands! Helene and Zillah say I’m insane! And I want to go
home!”
Like a short-necked animal elongated suddenly to the cervical
proportions of a giraffe, the Superintendent of Nurses reared up
from her stoop-shouldered desk-work, and stared forth in speechless
astonishment across the top of her spectacles.
Exuberantly impertinent, ecstatically self-conscious, Rae
Malgregor repeated her demand. To her parched mouth the very
taste of her own babbling impudence refreshed her like the shock
and prickle of cracked ice.
“I tell you, I want my own face again, and my own hands!” she
reiterated glibly. “I mean the face with the mortgage in it, and the
cinders—and the other human expressions,” she explained. “And the
nice, grubby country hands that go with that sort of a face.”
Very accusingly she raised her finger and shook it at the
Superintendent’s perfectly livid countenance.
“Oh, of course I know I wasn’t very much to look at; but at least
I matched. What my hands knew, I mean, my face knew. Pies or
plowing or May-baskets, what my hands knew my face knew. That’s
the way hands and faces ought to work together. But you—you with
all your rules and your bossing, and your everlasting ‘’S-’sh! ’S-’sh!’
you’ve snubbed all the know-anything out of my face and made my
hands nothing but two disconnected machines for somebody else to
run. And I hate you! You’re a monster! You’re a—Everybody hates
you!”
Mutely then she shut her eyes, bowed her head, and waited for
the Superintendent to smite her dead. The smite, she felt sure,
would be a noisy one. First of all, she reasoned, it would fracture her
skull. Naturally then, of course, it would splinter her spine. Later, in
all probability, it would telescope her knee-joints. And never indeed,
now that she came to think of it, had the arches of her feet felt less
capable of resisting so terrible an impact. Quite unconsciously she
groped out a little with one hand to steady herself against the edge
of the desk.
But the blow when it came was nothing but a cool finger tapping
her pulse.
“There! There!” crooned the Superintendent’s voice, with a most
amazing tolerance.
“But I won’t ‘there, there!’” snapped Rae Malgregor. Her eyes
were wide open again now, and extravagantly dilated.
The cool fingers on her pulse seemed to tighten a little.
“’S-’sh! ’S-’sh!” admonished the Superintendent’s mumbling lips.
“But I won’t ‘’S-’sh! ’S-’sh!’” stormed Rae Malgregor. Never before
in her three years’ hospital training had she seen her arch-enemy,
the Superintendent, so utterly disarmed of irascible temper and
arrogant dignity, and the sight perplexed and maddened her at one
and the same moment. “But I won’t ‘’S-’sh! ’S-’sh!’” Desperately she
jerked her curly blond head in the direction of the clock on the wall.
“Here it’s four o’clock now,” she cried, “and in less than four hours
you’re going to try and make me graduate, and go out into the world
—God knows where—and charge innocent people twenty-one dollars
a week, and washing, likelier than not, mind you, for these hands,”
she gestured, “that don’t coördinate at all with this face,” she
grimaced, “but with the face of one of the house doctors or the
Senior Surgeon or even you, who may be ’way off in Kamchatka
when I need him most!” she finished, with a confused jumble of
accusation and despair.
Still with unexplainable amiability the Superintendent whirled
back into place in her pivot-chair, and with her left hand, which had
all this time been rummaging busily in a lower desk drawer,
proffered Rae Malgregor a small fold of paper.
“Here, my dear,” she said, “here’s a sedative for you. Take it at
once. It will quiet you perfectly. We all know you’ve had very hard
luck this past month, but you mustn’t worry so about the future.”
The slightest possible tinge of purely professional manner crept back
into the older woman’s voice. “Certainly, Miss Malgregor, with your
judgment—”
“With my judgment?” cried Rae Malgregor. The phrase was like a
red rag to her. “With my judgment? Great heavens! that’s the whole
trouble! I haven’t got any judgment! I’ve never been allowed to
have any judgment! All I’ve ever been allowed to have is the
judgment of some flirty young medical student or the house doctor
or the Senior Surgeon or you!”
Her eyes were fairly piteous with terror.
“Don’t you see that my face doesn’t know anything?” she
faltered, “except just to smile and smile and smile and say ‘Yes, sir,’
‘No, sir,’ ‘Yes, sir’?” From curly blond head to square-toed, common-
sense shoes her little body began to quiver suddenly like the advent
of a chill. “Oh, what am I going to do,” she begged, “when I’m ’way
off alone—somewhere in the mountains or a tenement or a palace,
and something happens, and there isn’t any judgment round to tell
me what I ought to do?”
Abruptly in the doorway, as though summoned by some purely
casual flicker of the Superintendent’s thin fingers, another nurse
appeared.
“Yes, I rang,” said the Superintendent. “Go and ask the Senior
Surgeon if he can come to me here a moment, immediately.”
“The Senior Surgeon?” gasped Rae Malgregor. “The Senior
Surgeon?” With her hands clutching at her throat she reeled back
against the wall for support. Like a shore bereft in one second of its
tide, like a tree stripped in one second of its leafage, she stood
there, utterly stricken of temper or passion or any animating human
emotion whatsoever.
“Oh, now I’m going to be expelled! Oh, now I know I’m going to
be expelled!” she moaned listlessly.
Very vaguely into the farthest radiation of her vision she sensed
the approach of a man. Gray-haired, gray-suited, as grayly dogmatic
as a block of granite, the Senior Surgeon loomed up at last in the
doorway.
“I’m in a hurry,” he growled. “What’s the matter?”
Precipitously Rae Malgregor collapsed into the breach.
“Oh, there’s nothing at all the matter, sir,” she stammered. “It’s
only—it’s only that I’ve just decided that I don’t want to be a trained
nurse.”
With a gesture of ill-concealed impatience the Superintendent
shrugged the absurd speech aside.
“Dr. Faber,” she said, “won’t you just please assure Miss
Malgregor once more that the little Italian boy’s death last week was
in no conceivable way her fault—that nobody blames her in the
slightest, or holds her in any possible way responsible?”
“Why, what nonsense!” snapped the Senior Surgeon. “What—”
“And the Portuguese woman the week before that,” interrupted
Rae Malgregor, dully.
“Stuff and nonsense!” said the Senior Surgeon. “It’s nothing but
coincidence, pure coincidence. It might have happened to anybody.”
“And she hasn’t slept for almost a fortnight,” the Superintendent
confided, “nor touched a drop of food or drink, as far as I can make
out, except just black coffee. I’ve been expecting this breakdown for
some days.”
“And—the—young—drug-store—clerk—the—week—before—that,”
Rae Malgregor resumed with singsong monotony.
Bruskly the Senior Surgeon stepped forward and, taking the girl
by her shoulders, jerked her sharply round to the light, and, with
firm, authoritative fingers, rolled one of her eyelids deftly back from
its inordinately dilated pupil. Equally bruskly he turned away again.
“Nothing but moonshine!” he muttered. “Nothing in the world but
too much coffee dope taken on an empty stomach—‘empty brain,’ I’d
better have said. When will you girls ever learn any sense?” With
search-light shrewdness his eyes flashed back for an instant over the
haggard, gray lines that slashed along the corners of her quivering,
childish mouth. A bit temperishly he began to put on his gloves.
“Next time you set out to have a ‘brain-storm,’ Miss Malgregor,” he
suggested satirically, “try to have it about something more sensible
than imagining that anybody is trying to hold you personally
responsible for the existence of death in the world. Bah!” he
ejaculated fiercely. “If you are going to fuss like this over cases
hopelessly moribund from the start, what in thunder are you going
to do some fine day when, out of a perfectly clear and clean sky,
security itself turns septic, and you lose the President of the United
States or a mother of nine children—with a hang-nail?”
“But I wasn’t fussing, sir!” protested Rae Malgregor, with a timid
sort of dignity. “Why, it never had occurred to me for a moment that
anybody blamed me for anything.” Just from sheer astonishment her
hands took a new clutch into the torn, flapping corner of the motto
that she still clung desperately to even at this moment.
“For Heaven’s sake, stop crackling that brown paper!” stormed
the Senior Surgeon.
“But I wasn’t crackling the brown paper, sir! It’s crackling itself,”
persisted Rae Malgregor, very softly. The great blue eyes that lifted
to his were brimming full of misery. “Oh, can’t I make you
understand, sir?” she stammered. Appealingly she turned to the
Superintendent. “Oh, can’t I make anybody understand? All I was
trying to say, all I was trying to explain, was that I don’t want to be
a trained nurse—after all.”
“Why not?” demanded the Senior Surgeon, with a rather noisy
click of his glove fasteners.
“Because—my face is tired,” said the girl, quite simply.
The explosive wrath on the Senior Surgeon’s countenance
seemed to be directed suddenly at the Superintendent.
“Is this an afternoon tea?” he asked tartly. “With six major
operations this morning, and a probable meningitis diagnosis ahead
of me this afternoon, I think I might be spared the babblings of an
hysterical nurse.” Casually over his shoulder he nodded at the girl.
“You’re a fool,” he said, and started for the door.
Just on the threshold he turned abruptly and looked back. His
forehead was furrowed like a corduroy road, and the one rampant
question in his mind at the moment seemed to be mired hopelessly
between his bushy eyebrows.
“Lord!” he exclaimed a bit flounderingly, “are you the nurse that
helped me last week on that fractured skull?”
“Yes, sir,” said Rae Malgregor.
Jerkily the Senior Surgeon retraced his footsteps into the office
and stood facing her as though with some really terrible accusation.
“And the freak abdominal?” he quizzed sharply. “Was it you who
threaded that needle for me so blamed slowly and calmly and surely,
while all the rest of us were jumping up and down and cursing you
for no brighter reason than that we couldn’t have threaded it
ourselves if we’d had all eternity before us and all hell bleeding to
death?”
“Y-e-s,” said Rae Malgregor.
Quite bluntly the Senior Surgeon reached out and lifted one of
her hands to his scowling professional scrutiny.
“God!” he attested, “what a hand! You’re a wonder. Under proper
direction you’re a wonder. It was like myself working with twenty
fingers and no thumbs. I never saw anything like it.”
Almost boyishly the embarrassed flush mounted to his cheeks as
he jerked away again. “Excuse me for not recognizing you,” he
apologized gruffly, “but you girls all look so much alike!”
As though the eloquence of Heaven itself had suddenly
descended upon a person hitherto hopelessly tongue-tied, Rae
Malgregor lifted an utterly transfigured face to the Senior Surgeon’s
grimly astonished gaze.
“Yes, yes, sir!” she cried joyously; “that’s just exactly what the
trouble is; that’s just exactly what I was trying to express, sir: my
face is all worn out trying to ‘look alike.’ My cheeks are almost
sprung with artificial smiles. My eyes are fairly bulging with unshed
tears. My nose aches like a toothache trying never to turn up at
anything. I’m smothered with the discipline of it. I’m choked with the
affectation. I tell you, I just can’t breathe through a trained nurse’s
face any more. I tell you, sir, I’m sick to death of being nothing but a
type. I want to look like myself. I want to see what life could do to a
silly face like mine if it ever got a chance. When other women are
crying, I want the fun of crying. When other women look scared to
death, I want the fun of looking scared to death.” Hysterically again,
with shrewish emphasis, she began to repeat: “I won’t be a nurse! I
tell you I won’t! I won’t!”
“Pray what brought you so suddenly to this remarkable
decision?” scoffed the Senior Surgeon.
“A letter from my father, sir,” she confided more quietly—“a letter
about some dogs.”
“Dogs?” hooted the Senior Surgeon.
“Yes, sir,” said the White Linen Nurse. A trifle speculatively for an
instant she glanced at the Superintendent’s face and then back
again to the Senior Surgeon’s. “Yes, sir,” she repeated with
increasing confidence, “up in Nova Scotia my father raises hunting-
dogs. Oh, no special fancy kind, sir,” she hastened in all honesty to
explain, “just dogs, you know; just mixed dogs, pointers with curly
tails, and shaggy-coated hounds, and brindled spaniels, and all that
sort of thing; just mongrels, you know, but very clever. And people,
sir, come all the way from Boston to buy dogs of him, and once a
man came way from London to learn the secret of his training.”
“Well, what is the secret of his training?” quizzed the Senior
Surgeon with the sudden eager interest of a sportsman. “I should
think it would be pretty hard,” he acknowledged, “in a mixed gang
like that to decide just what particular game was suited to which
particular dog.”
“Yes, that’s just it, sir,” beamed the White Linen Nurse. “A dog, of
course, will chase anything that runs,—that’s just dog,—but when a
dog really begins to care for what he’s chasing, he—wags! That’s
hunting. Father doesn’t calculate, he says, on training a dog on
anything he doesn’t wag on.”
“Yes, but what’s that got to do with you?” asked the Senior
Surgeon, a bit impatiently.
With ill-concealed dismay the White Linen Nurse stood staring
blankly at the Senior Surgeon’s gross stupidity.
“Why, don’t you see?” she faltered. “I’ve been chasing this
nursing job three whole years now, and there’s no wag to it.”
“Oh, hell!” said the Senior Surgeon. If he hadn’t said “Oh, hell!”
he would have grinned. And it hadn’t been a grinny day, and he
certainly didn’t intend to begin grinning at any such late hour as that
in the afternoon. With his dignity once reassured, he then relaxed a
trifle. “For Heaven’s sake, what do you want to be?” he asked not
unkindly.
With an abrupt effort at self-control Rae Malgregor jerked her
head into at least the outer semblance of a person lost in almost
fathomless thought.
“Why, I’m sure I don’t know, sir,” she acknowledged worriedly.
“But it would be a great pity, I suppose, to waste all the grand
training that’s gone into my hands.” With sudden conviction her limp
shoulders stiffened a trifle. “My oldest sister,” she stammered,
“bosses the laundry in one of the big hotels in Halifax, and my
youngest sister teaches school in Moncton. But I’m so strong, you
know, and I like to move things round so, and everything, maybe I
could get a position somewhere as general housework girl.”
With a roar of amusement as astonishing to himself as to his
listeners, the Senior Surgeon’s chin jerked suddenly upward.
“You’re crazy as a loon!” he confided cordially. “Great Scott! If
you can work up a condition like this on coffee, what would you do
on malted milk?” As unheralded as his amusement, gross irritability
overtook him again. “Will—you—stop—rattling that brown paper?”
he thundered at her.
As innocently as a child she rebuffed the accusation and ignored
the temper.
“But I’m not rattling it, sir!” she protested. “I’m simply trying to
hide what’s on the other side of it.”
“What is on the other side of it?” demanded the Senior Surgeon,
bluntly.
With unquestioning docility the girl turned the paper around.
From behind her desk the austere Superintendent twisted her
neck most informally to decipher the scrawling hieroglyphics. “Don’t
Ever Be Bumptious!” she read forth jerkily with a questioning,
incredulous sort of emphasis.
“Don’t ever be bumptious!” squinted the Senior Surgeon
perplexedly through his glass.
“Yes,” said Rae Malgregor, very timidly. “It’s my motto.”
“Your motto?” sniffed the Superintendent.
“Your motto?” chuckled the Senior Surgeon.
“Yes, my motto,” repeated Rae Malgregor, with the slightest
perceptible tinge of resentment. “And it’s a perfectly good motto,
too. Only, of course, it hasn’t got any style to it. That’s why I didn’t
want the girls to see it,” she confided a bit drearily. Then palpably
before their eyes they saw her spirit leap into ineffable pride. “My
father gave it to me,” she announced briskly, “and my father said
that, when I came home in June, if I could honestly say that I’d
never once been bumptious all my three years here, he’d give me a
heifer. And—”
“Well, I guess you’ve lost your heifer,” said the Senior Surgeon,
bluntly.
“Lost my heifer?” gasped the girl. Big-eyed and incredulous, she
stood for an instant staring back and forth from the Superintendent’s
face to the Senior Surgeon’s. “You mean,” she stammered—“you
mean that I’ve been bumptious just now? You mean that, after all
these years of meachin’ meekness, I’ve lost?”
Plainly even to the Senior Surgeon and the Superintendent the
bones in her knees weakened suddenly like knots of tissue-paper. No
power on earth could have made her break discipline by taking a
chair while the Senior Surgeon stood, so she sank limply down to
the floor instead, with two great solemn tears welling slowly through
the fingers with which she tried to cover her face.
“And the heifer was brown, with one white ear; it was awful’
cunning,” she confided mumblingly. “And it ate from my hand, all
warm and sticky, like loving sand-paper.” There was no protest in her
voice, or any whine of complaint, but merely the abject submission
to fate of one who from earliest infancy had seen other crops
blighted by other frosts. Then tremulously, with the air of one who
just as a matter of spiritual tidiness would purge her soul of all sad
secrets, she lifted her entrancing, tear-flushed face from her strong,
sturdy, utterly unemotional fingers and stared with amazing
blueness, amazing blandness, into the Senior Surgeon’s scowling
scrutiny.
ebookbell.com