Buy ebook Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely cheap price
Buy ebook Programming and Mathematical Thinking A Gentle Introduction to Discrete Math Featuring Python 1st Edition Allan M. Stavely cheap price
com
https://ebookname.com/product/programming-and-mathematical-
thinking-a-gentle-introduction-to-discrete-math-featuring-
python-1st-edition-allan-m-stavely/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookname.com/product/programming-in-python-3-a-complete-
introduction-to-the-python-language-2nd-edition-summerfield/
ebookname.com
https://ebookname.com/product/a-gentle-introduction-to-
optimization-1st-edition-b-guenin/
ebookname.com
https://ebookname.com/product/a-gentle-introduction-to-stata-2018th-
edition-alan-c-acock/
ebookname.com
https://ebookname.com/product/experimental-approaches-to-diabetic-
retinopathy-frontiers-in-diabetes-vol-20-1st-edition-h-p-hammes/
ebookname.com
Building High Performance Business Relationships Rescue
Improve and Transform Your Most Valuable Assets 1st
Edition Tony Lendrum
https://ebookname.com/product/building-high-performance-business-
relationships-rescue-improve-and-transform-your-most-valuable-
assets-1st-edition-tony-lendrum/
ebookname.com
https://ebookname.com/product/in-rivers-lakes-and-ponds-under-the-
microscope-1st-edition-sabrina-crewe/
ebookname.com
https://ebookname.com/product/elements-of-set-theory-enderton/
ebookname.com
https://ebookname.com/product/nanomedicine-design-of-particles-
sensors-motors-implants-robots-and-devices-mark-j-schulz/
ebookname.com
https://ebookname.com/product/israel-jordan-and-palestine-the-two-
state-imperative-asher-susser/
ebookname.com
The Phenomenon of Obama and the Agenda for Education Can
Hope Audaciously Trump Neoliberalism 1st Edition Paul R.
Carr
https://ebookname.com/product/the-phenomenon-of-obama-and-the-agenda-
for-education-can-hope-audaciously-trump-neoliberalism-1st-edition-
paul-r-carr/
ebookname.com
Programming and Mathematical
Thinking
A Gentle Introduction to Discrete Math
Featuring Python
Allan M. Stavely
First Edition
Content of this book available under the Creative Commons Attribution-Noncommercial-ShareAlike License. See
http://creativecommons.org/licenses/by-nc-sa/4.0/ for details.
Stavely, Allan M
Programming and mathematical thinking: a gentle introduction to discrete
math featuring Python / Allan M. Stavely.
xii, 246 p.: ill. ; 28 cm
ISBN 978-1-938159-00-8 (pbk.) — 978-1-938159-01-5 (ebook)
1. Computer science — Mathematics. 2. Mathematics — Discrete
Mathematics. 3. Python (Computer program language).
Published by The New Mexico Tech Press, a New Mexico nonprofit corporation
i
ii
Table of Contents
Preface ........................................................................................................ vii
1. Introduction ............................................................................................. 1
1.1. Programs, data, and mathematical objects ..................................... 1
1.2. A first look at Python .................................................................... 3
1.3. A little mathematical terminology ................................................ 10
2. An overview of Python ........................................................................... 17
2.1. Introduction ................................................................................. 17
2.2. Values, types, and names ............................................................. 18
2.3. Integers ........................................................................................ 19
2.4. Floating-point numbers ................................................................ 23
2.5. Strings .......................................................................................... 25
3. Python programs .................................................................................... 29
3.1. Statements ................................................................................... 29
3.2. Conditionals ................................................................................ 31
3.3. Iterations ..................................................................................... 35
4. Python functions ..................................................................................... 41
4.1. Function definitions ..................................................................... 41
4.2. Recursive functions ...................................................................... 43
4.3. Functions as values ...................................................................... 45
4.4. Lambda expressions ..................................................................... 48
5. Tuples ..................................................................................................... 51
5.1. Ordered pairs and n-tuples .......................................................... 51
5.2. Tuples in Python .......................................................................... 52
5.3. Files and databases ...................................................................... 54
6. Sequences ............................................................................................... 57
6.1. Properties of sequences ................................................................ 57
6.2. Monoids ...................................................................................... 59
6.3. Sequences in Python ..................................................................... 64
6.4. Higher-order sequence functions .................................................. 67
6.5. Comprehensions .......................................................................... 73
6.6. Parallel processing ....................................................................... 74
7. Streams ................................................................................................... 83
7.1. Dynamically-generated sequences ................................................ 83
7.2. Generator functions ..................................................................... 85
iii
Programming and Mathematical Thinking
iv
List of Examples
1.1. Finding a name ...................................................................................... 4
1.2. Finding an email address ....................................................................... 7
1.3. Average of a collection of observations .................................................. 8
6.1. Finding a name again, in functional style ............................................. 71
6.2. Average of observations again, in functional style ................................ 72
7.1. Combinations using a generator function ............................................ 89
8.1. Finding job candidates using set operations ....................................... 117
8.2. Job candidates again, with different input files .................................. 122
9.1. Finding given words in a document ................................................... 139
9.2. A memoized function: the nth Fibonacci number ................................ 144
9.3. Number of students in each major field ............................................. 149
10.1. Distances using symmetry and reflexivity ......................................... 159
11.1. The MovingAverage class .................................................................. 191
11.2. The MovingAverage class, version 2 ................................................. 193
11.3. The Pushbutton class ....................................................................... 204
11.4. A state machine for finding fields in a string .................................... 206
11.5. Code that uses a FieldsStateMachine ............................................. 207
11.6. A state machine for finding fields, version 2 .................................... 209
v
vi
Preface
My mission in this book is to encourage programmers to think mathematically
as they develop programs.
1
This paragraph and the example that follows are adapted from a previous book: Allan M. Stavely,
Toward Zero-Defect Programming (Reading, Mass.: Addison Wesley Longman, 1999), 142–143.
vii
First I'll read the first web page and store all the URLs I find in a list.
Then I'll read the second web page and, every time I find a URL, search
the list for it. But wait: I don't want to include the same URL in my
result more than once. I'll keep a second list of the URLs that I've
already found in both web pages, and search that before I search the
list of URLs from the first web page.
The URLs in a web page are a set. I'll read each web page and build
up the set of URLs in each using set insertion. Then I can get the URLs
common to both web pages by using set intersection.
Either approach will work, but the second is conceptually simpler, and it will
probably be more straightforward to implement. In fact, once the problem is
described in mathematical terms, most of the design work is already done.
viii
programmers never learn, and we'll see how to use them to create simple and
elegant solutions to programming problems.
For example, one recurring theme in the book is the concept of a monoid. It
turns out that monoids (more than, for example, groups and semigroups) are
ubiquitous in the data types and data structures that programmers use most
often. I emphasize the extent to which all monoids behave alike and how
concepts and algorithms can be transferred from one to another.
Otherwise, the ideal reader is someone who has had at least some experience
with programming, using either Python or another programming language.
In fact, I hope that some of my readers will be quite experienced programmers
who may never have been through a modern, mathematically-oriented program
of study in computer science. If you are such a person, you'll see many ideas
that will probably be new to you and that will probably improve your
programming.
At the end of most chapters is a set of exercises. Instructors can use these
exercises in laboratory sessions or as homework exercises, and some can be
used as starting points for class discussions. Many instructors will want to
supplement these exercises with their own extended programming assignments.
ix
exception handling, parallel computing, distributed computing, various
advanced data structures and algorithms, object-oriented programming, and
state machines.
• the extensive standard library and the many other libraries that are
commonly available
x
• almost all “special” attributes and methods (those whose names start and
end with a double underbar) that expose internal details of objects
Any programmer who uses Python extensively should learn about all of these
features of the language. I recommend that such a person peruse a
comprehensive Python textbook or reference manual.2
In any case, there is more to Python than I present in this book. So whenever
you think to yourself, “I see I can do x with Python — can I do y too?”, maybe
you can. Again, you can find out in a Python textbook or reference manual.
This book will describe the most modern form of Python, called Python 3. It
may be that the version of Python that you have on your computer is a version
of Python 2, such as Python 2.3 or 2.7. There are only a few differences that
you may see as you use the features of Python mentioned in this book. Here
are the most important differences (for our purposes) between Python 3 and
Python 2.7, the final and most mature version of Python 2:
2
As of the time of writing, comprehensive Python documentation, including the official reference
manual, can be found at http://docs.python.org.
xi
• In Python 2, characters in a string are ASCII and not Unicode by default;
there is a separate Unicode type.
Versions of Python earlier than 2.7 have more incompatibilities than these:
check the documentation for the version you use.
In the chapters that follow I usually use the author's “we” for a first-person
pronoun, but I say “I” when I am expressing my personal opinion, speaking
of my own experiences, and so on. And I follow this British punctuation
convention: punctuation is placed inside quotation marks only if it is part of
what is being quoted. Besides being more logical (in my opinion), this treatment
avoids ambiguity. For example, here's how many American style guides tell
you to punctuate:
Is the “.” part of what you would write, or not? It can make a big difference,
as any programmer knows. There is no ambiguity this way:
I am grateful to all the friends and colleagues who have given me help,
suggestions, and support in this writing project, most prominently Lisa
Beinhoff, Horst Clausen, Jeff Havlena, Peter Henderson, Daryl Lee, Subhashish
Mazumdar, Angelica Perry, Steve Schaffer, John Shipman, and Steve Simpson.
3
Harold Abelson and Gerald Jay Sussman with Julie Sussman, Structure and Interpretation of Computer
Programs (Cambridge, Mass.: The MIT Press, 1985).
xii
Chapter 1
Introduction
1.1. Programs, data, and mathematical objects
A master programmer learns to think of programs and data at many levels of
detail at different times. Sometimes the appropriate level is bits and bytes and
machine words and machine instructions. Often, though, it is far more
productive to think and work with higher-level data objects and higher-level
program constructs.
Ultimately, at the lowest level, the program code that runs on our computers
is patterns of bits in machine words. In the early days of computing, all
programmers had to work with these machine-level instructions all the time.
Now almost all programmers, almost all the time, use higher-level
programming languages and are far more productive as a result.
The thesis of this book is that, very often, mathematical objects are exactly
the higher-level data objects we want. Some of these mathematical objects are
numbers, but many — the objects of discrete mathematics — are quite different,
as we will see.
So this book will present programming as done at a high level and with a
mathematical slant. Here's how we will view programs and data:
Programs will be text, in a form (which we call “syntax”) that does not look
much like sequences of machine instructions. On the contrary, our programs
will be in a higher-level programming language, whose syntax is designed for
1
Programs, data, and mathematical objects
The data in our programs will reside in a computer's main storage (which we
often metaphorically call “memory”) that may look like a long sequence of
machine words, but most of the time we will not be concerned with exactly
how our data objects are represented there; the data objects will look like
mathematical objects from our point of view. We assume that the main storage
is quite large, usually large enough for all the data we might want to put into
it, although not infinite in size.
We will assume that what looks simple in a program is also reasonably simple
at the level of bits and bytes and machine instructions. There will be a
straightforward correspondence between the two levels; a computer science
student or master programmer will learn how to construct implementations
of the higher-level constructs from low-level components, but from other
books than this one. We will play fair; we will not present any program
construct that hides lengthy computations or a mass of complexity in its low-
level implementation. Thus we will be able to make occasional statements
about program efficiency that may not be very specific, but that will at least
be meaningful. And you can be assured that the programming techniques that
we present will be reasonable to use in practical programs.
2
A first look at Python
Python falls into several categories of programming language that you might
hear programmers talk about:
• It's a scripting language. This term doesn't have a precise definition, but
generally it means a language that lends itself to writing little programs
called scripts, perhaps using the kinds of commands that you might type
into a command-line window on a typical computer system. For example,
some scripts are programs that someone writes on the spur of the moment
to do simple manipulations on files or to extract data from them. Some
scripts control other programs, and system administrators often use scripting
languages to combine different functions of a computer's operating system
to perform a task. We'll see examples of Python scripts shortly. (Other
scripting languages that you might encounter are Perl and Ruby.)
• It's a very high-level language, or at least it has been called that. This is
another concept that doesn't have a precise definition, but in the case of
Python it means that mathematical objects are built into the core of the
language, more so than in most other programming languages. Furthermore,
in many cases we'll be able to work with these objects in notation that
3
A first look at Python
Depending on how you use it, Python can be a language of any of these kinds
or all of them at once.
Let's look at a few simple Python programs, to give you some idea of what
Python looks like.
The first program is the kind of very short script that a Python programmer
might write to use just once and then discard. Let's say that you have just
attended a lecture, and you met someone named John, but you can't remember
his last name. Fortunately, the lecturer has a file of the names of all the
attendees and has made that file available to you. Let's say that you have put
that file on your computer and called it “names”. There are several hundred
names in the file, so you'd like to have the computer do the searching for you.
Example 1.1 shows a Python script that will display all the lines of the file
that start with the letters “John”.
You may be able to guess (and guess correctly) what most of the parts of this
script do, especially if you have done any programming in another
programming language, but I'll explain the script a line at a time. Let's not
bother with the fine points, such as what the different punctuation marks
mean in Python; you'll learn all that later. For now, I'll just explain each line
in very general terms.
file = open("names")
4
A first look at Python
This line performs an operation called “opening” a file on our computer. It's
a rather complicated sequence of operations, but the general idea is this: get
a file named “names” from our computer's file system and make it available
for our program to read from. We give the name file to the result.
Here and in the other examples in this book, we won't worry about what
might happen if the open operation fails: for example, if there is no file with
the given name, or if the file can't be read for some reason. Serious Python
programmers need to learn about the features of Python that are used for
handling situations like these, and need to include code for handling
exceptional situations in most programs that do serious work.1 In a simple
one-time script like this one, though, a Python programmer probably wouldn't
bother. In any case, we'll omit all such code in our examples, simply because
that code would only distract from the points that we are trying to make.
for line in file:
This means, “For each line in file, do what comes next.” More precisely, it
means this: take each line of file, one at a time. Each time, give that line the
name line, and then do the lines of the program that come next, the lines that
are indented.
if line.startswith("John"):
This means what it appears to mean: if line starts with the letters “John”, do
what comes next.
print(line)
Since the line of the file starts with “John”, it's one that we want to see, and
this is what displays the line. On most computers, we can run the program in
a window on our computer's screen, and print will display its results in that
window.
1
The term for such code is “exception handling”, in case you want to look up the topic in Python
documentation. Handling exceptions properly can be complicated, sometimes involving difficult design
decisions, which is why we choose to treat the topic as beyond the scope of the current book.
5
A first look at Python
If you run the program, here's what you might see (depending, of course, on
what is in the file names).
John Atencio
John Atkins
Johnson Cummings
John Davis
John Hammerstein
And so on. This is pretty much as you might expect, although there may be
a couple of surprises here. Why is this output double-spaced? Well, it turns
out that each line of the file ends with a “new line” character, and the print
operation adds another. (As you learn more details of Python, you'll probably
learn how to make output like this come out single-spaced if that's what you'd
prefer.) And why is there one person here with the first name “Johnson”
instead of “John”? That shouldn't be a surprise, since our simple little program
doesn't really find first names in a line: it just looks for lines in which the first
four letters are “John”. Anyway, this output is probably good enough for a
script that you're only going to use once, especially if it reminds you that the
person you were thinking of is John Davis.
Now let's say that you'd like to get in touch with John Davis. Your luck
continues: the lecturer has provided another file containing the names and
email addresses of all the attendees. Each line of the file contains a person's
name and that person's email address, separated by a comma.
Suppose you transfer that file to your computer and give it the name “emails”.
Then Example 1.2 shows a Python script that will find and display John
Davis's email address if it's in the file.
6
A first look at Python
These lines are very much like the first two lines of the previous program; the
only difference is the name of the file in the first line. In fact, this pattern of
code is common in programs that read a file and do something with every line
of it.
name, email = line.split(",")
The part line.split(",") splits line into two pieces at the comma. The result
is two things: the piece before the comma and the piece after the comma. We
give the names “name” and “email” to those two things.
if name == "John Davis":
This says: if name equals (in other words, is the same as) “John Davis”, do
what comes next. Python uses “==”, two adjacent equals-signs, for this kind
of comparison. You might think that just a single equals-sign would mean
“equals”, but Python uses “=” to associate a name with a thing, as we have
seen. So, to avoid any possible ambiguity, Python uses a different symbol for
comparing two things for equality.
print(email)
As our final example, let's take a very simple computational task: finding the
average of a collection of numbers. They might be a scientist's measurements
7
A first look at Python
Let's say, for the sake of the example, that they are temperatures. You have
a thermometer outside your window, and you read it at the same time each
day for a month. You record each temperature to the nearest degree, so all
your observations are whole numbers (the mathematical term for these is
“integers”). You put the numbers into a file on your computer, perhaps using
a text-editing or word-processing program; let's say that the name of the file
is “observations”. At the end of the month, you want to calculate the average
temperature for the month.
Example 1.3 shows a Python program that will do that computation. It's a
little longer than the previous two programs, but it's still short and simple
enough that we might call it a “script”.
file = open("observations")
for line in file:
n = int(line)
sum += n
count += 1
print(sum/count)
To compute the average of the numbers in the file, we need to find the sum
of all the numbers and also count how many there are. Here we give the names
8
A first look at Python
sum and count to those two values. We start both the sum and the count at
zero.
file = open("observations")
for line in file:
As in the previous two programs, these lines say: open the file that we want
and then, for each line of the file, do what comes next. Specifically, do the
lines that are indented, the next three lines.
n = int(line)
In Python, “+=” means “add the thing on the right to the thing on the left”.
So, “sum += n” means “add n to sum” and “count += 1” means “add 1 to
count”. This is the obvious way to accumulate the running sum and the running
count of the numbers that the program has seen so far.
print(sum/count)
This step is done after all the numbers in the file have been summed and
counted. It displays the result of the computation: the average of the numbers,
which is sum divided by count.
Notice, by the way, that we've used blank lines to divide the lines of the
program into logical groups. You can do this in Python, and programmers
often do. This doesn't affect what the program does, but it might make the
program a little easier for a person to read and understand.
So now you've seen three very short and simple Python programs. They aren't
entirely typical of Python programs, though, because they illustrate only a
few of the most basic parts of the Python language. Python has many more
9
A little mathematical terminology
features, and you'll learn about many of them in the remaining chapters of
this book. But these programs are enough examples of Python for now.
The first term is set. A set is just an unordered collection of different things.
For example, we can speak of the set of all the people in a room, or the set of
all the books that you have read this year, or the set of different items that
are for sale in a particular shop.
For example, we can speak of the sequence of digits in your telephone number
or the sequence of letters in your surname. Unlike a set, a sequence doesn't
have the property that all the things in it are necessarily different. For example,
many telephone numbers contain some digit more than once.
You may have heard the word “set” used in a mathematical context, or you
may know the word just from its ordinary English usage. It may seem strange
to call the word “sequence” a mathematical term, but it turns out that
10
A little mathematical terminology
sequences have some mathematical properties that we'll want to be aware of.
For now, just notice the differences between the concepts “set” and “sequence”.
Let's try applying these mathematical concepts to the sample Python programs
that we've just seen. In each of them, what kind of mathematical object is the
data that the program operates on?
First, notice that each program operates on a file. A file, at least as a Python
program sees it, is a sequence of lines. Code like this is very common in Python
programs that read files a line at a time:
file = open("observations")
for line in file:
Let's take the file of names in our first example (Example 1.1). In terms of the
information that we want to get from it, the file is a collection of names. What
kind of collection? We don't care about the order of names in it; we just want
to see all the names that start with “John”. So, assuming that our lecturer
hasn't included any name twice by mistake, the collection is a set as far as
we're concerned.
In fact, both the input and the output of this program are sets. The input is
the set of names of people who attended the lecture. The output is the set of
members of that input set that start with the letters “John”. In mathematical
terminology, the output set is a subset of the input set.
11
Random documents with unrelated
content Scribd suggests to you:
CHAPTER XXV.
"The inside of the coach contains only four places. The seat
of the coachman, and another seat placed immediately
behind it, admit of six persons, and two seats facing each
other, at the hind wheels, afford places for six or eight more.
These seats are fixed over boots or boxes for stowing away
the luggage. Such parcels as these cannot contain are placed
on the imperial.
"6. That they are not (or need not be, if properly
constructed) nuisances to the public.
"7. That they will become a speedier and cheaper mode of
conveyance than carriages drawn by horses.
Chorus.
"'William Clayton.
"'Witnesses: Joseph Gordon, G. Wood, George Whalley.'"
"Now I have shown you the dark side of my wife, and told
you her faults and her failings, I will introduce the bright and
sunny side of her, and explain her qualifications and her
goodness. She can read novels and milk cows; she can laugh
and weep with the same ease that you can take a glass of ale
when thirsty; indeed, gentlemen, she reminds me of what the
poet says of women in general—
"She can make butter and scold the maid; she can sing
Moore's Melodies, and plait her frills and caps; she cannot
make rum, gin, or whisky, but she is a good judge of the
quality from long experience in tasting them. I therefore offer
her, with all her perfections and imperfections, for the sum of
50s.
"After an hour or two, she was purchased by Henry Mears,
a pensioner, for the sum of 20s. and a Newfoundland dog.
The happy people immediately left town together, amidst the
shouts and huzzas of the multitude, in which they were joined
by Thompson, who, with the greatest good humour
imaginable, proceeded to put the halter which his wife had
taken off round the neck of his Newfoundland dog, and then
proceeded to the first public-house, where he spent the
remainder of the day."
"Next day came, and found the seller, the purchaser, and
their witnesses once more assembled, discussing at once the
terms of agreement and a can of grog. Some of the witnesses
seemed to think that the joke was carried far enough, and
proposed that the whole proceedings should be nullified on
the host forfeiting £1, to be 'melted,' in the house; but the
host was too well up to trap to be wheedled out of his £20,
and saddled with his wife to boot; he therefore persisted in
the fulfilment of the contract, and, as the purchaser was
equally averse to a rue bargain, arrangements were put in
operation to complete the transaction.
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.
ebookname.com