Immediate download Learn to Code by Solving Problems A Python Programming Primer 1st Edition Daniel Zingaro ebooks 2024
Immediate download Learn to Code by Solving Problems A Python Programming Primer 1st Edition Daniel Zingaro ebooks 2024
com
https://ebookmeta.com/product/learn-to-code-by-solving-
problems-a-python-programming-primer-1st-edition-daniel-
zingaro-2/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/learn-to-code-by-solving-problems-a-
python-programming-primer-1st-edition-daniel-zingaro/
ebookmeta.com
https://ebookmeta.com/product/learn-to-code-by-solving-problems-a-
python-programming-primer-1st-edition-daniel-zingaro-3/
ebookmeta.com
https://ebookmeta.com/product/learn-to-code-by-solving-problems-
daniel-zingaro/
ebookmeta.com
https://ebookmeta.com/product/rasch-measurement-theory-analysis-
in-r-1st-edition-cheng-hua/
ebookmeta.com
Beneath Cold Earth 1st Edition M S Morris
https://ebookmeta.com/product/beneath-cold-earth-1st-edition-m-s-
morris/
ebookmeta.com
https://ebookmeta.com/product/fearless-like-us-1st-edition-krista-
ritchie/
ebookmeta.com
https://ebookmeta.com/product/dating-the-virgin-1st-edition-piper-
cook/
ebookmeta.com
https://ebookmeta.com/product/empowerment-for-teaching-excellence-
through-virtuous-agency-1st-edition-lotter-hennie/
ebookmeta.com
https://ebookmeta.com/product/shaw-1st-edition-milly-taiden/
ebookmeta.com
LEARN TO CODE BY
SOLVING PROBLEMS
A Python Programming Primer
by Daniel Zingaro
San Francisco
LEARN TO CODE BY SOLVING PROBLEMS. Copyright © 2021 by Daniel
Zingaro.
All rights reserved. No part of this work may be reproduced or transmitted in any
form or by any means, electronic or mechanical, including photocopying,
recording, or by any information storage or retrieval system, without the prior
written permission of the copyright owner and the publisher.
No Starch Press and the No Starch Press logo are registered trademarks of No
Starch Press, Inc. Other product and company names mentioned herein may be
the trademarks of their respective owners. Rather than use a trademark symbol
with every occurrence of a trademarked name, we are using the names only in an
editorial fashion and to the benefit of the trademark owner, with no intention of
infringement of the trademark.
The information in this book is distributed on an “As Is” basis, without warranty.
While every precaution has been taken in the preparation of this work, neither
the author nor No Starch Press, Inc. shall have any liability to any person or
entity with respect to any loss or damage caused or alleged to be caused directly
or indirectly by the information contained in it.
To Dad, for the computer code
and
To Mom, for the teacher code
About the Author
Dr. Daniel Zingaro is an associate teaching professor of computer
science and award-winning teacher at the University of Toronto. His
main area of research is computer science education, where he studies
how students learn (and sometimes don’t learn) computer science
material. He is the author of Algorithmic Thinking (No Starch Press,
2021), a book that helps learners understand and use algorithms and data
structures.
About the Technical Reviewer
Luke Sawczak is a frequent freelance editor and hobby programmer; his
favorite projects include a prose-to-poetry converter, a visual aid for
cutting the right number of slices of cake, and a version of Boggle that
uses numbers made for math tutors. He currently teaches French and
English on the outskirts of Toronto. He also writes poetry and composes
for the piano, which he would do for a living if he could. He can be
found online at https://sawczak.com/.
BRIEF CONTENTS
Acknowledgments
Introduction
Chapter 1: Getting Started
Chapter 2: Making Decisions
Chapter 3: Repeating Code: Definite Loops
Chapter 4: Repeating Code: Indefinite Loops
Chapter 5: Organizing Values Using Lists
Chapter 6: Designing Programs with Functions
Chapter 7: Reading and Writing Files
Chapter 8: Organizing Values Using Sets and Dictionaries
Chapter 9: Designing Algorithms with Complete Search
Chapter 10: Big O and Program Efficiency
Afterword
Appendix: Problem Credits
Index
CONTENTS IN DETAIL
ACKNOWLEDGMENTS
INTRODUCTION
Online Resources
Who This Book Is For
Why Learn Python?
Installing Python
Windows
macOS
Linux
How to Read This Book
Using Programming Judges
Making Your Programming Judge Accounts
The DMOJ Judge
The Timus Judge
The USACO Judge
About This Book
1
GETTING STARTED
What We’ll Be Doing
The Python Shell
Windows
macOS
Linux
Problem #1: Word Count
The Challenge
Input
Output
Strings
Representing Strings
String Operators
String Methods
Integer and Floating-Point Numbers
Variables
Assignment Statement
Changing Variable Values
Counting the Words Using a Variable
Reading Input
Writing Output
Solving the Problem: A Complete Python Program
Launching a Text Editor
The Program
Running the Program
Submitting to the Judge
Problem #2: Cone Volume
The Challenge
Input
Output
More Math in Python
Accessing Pi
Exponents
Converting Between Strings and Integers
Solving the Problem
Summary
Chapter Exercises
Notes
2
MAKING DECISIONS
Problem #3: Winning Team
The Challenge
Input
Output
Conditional Execution
The Boolean Type
Relational Operators
The if Statement
if by Itself
if with elif
if with else
Solving the Problem
Problem #4: Telemarketers
The Challenge
Input
Output
Boolean Operators
or Operator
and Operator
not Operator
Solving the Problem
Comments
Input and Output Redirection
Summary
Chapter Exercises
Notes
3
REPEATING CODE: DEFINITE LOOPS
Problem #5: Three Cups
The Challenge
Input
Output
Why Loops?
for Loops
Nesting
Solving the Problem
Problem #6: Occupied Spaces
The Challenge
Input
Output
A New Kind of Loop
Indexing
Range for loops
Range for Loops Through Indices
Solving the Problem
Problem #7: Data Plan
The Challenge
Input
Output
Looping to Read Input
Solving the Problem
Summary
Chapter Exercises
Notes
4
REPEATING CODE: INDEFINITE LOOPS
Problem #8: Slot Machines
The Challenge
Input
Output
Exploring a Test Case
A Limitation of for loops
while loops
Using while loops
Nesting Loops in Loops
Adding Boolean Operators
Solving the Problem
The Mod Operator
F-Strings
Problem #9: Song Playlist
The Challenge
Input
Output
String Slicing
Solving the Problem
Problem #10: Secret Sentence
The Challenge
Input
Output
Another Limitation of for loops
while Loops Through Indices
Solving the Problem
break and continue
break
continue
Summary
Chapter Exercises
Notes
5
ORGANIZING VALUES USING LISTS
Problem #11: Village Neighborhood
The Challenge
Input
Output
Why Lists?
Lists
List Mutability
Learning About Methods
List Methods
Adding to a List
Sorting a List
Removing Values from a List
Solving the Problem
Avoiding Code Duplication: Two More Solutions
Using a Huge Size
Building a List of Sizes
Problem #12: School Trip
The Challenge
Input
Output
A Catch
Splitting Strings and Joining Lists
Splitting a String into a List
Joining a List into a String
Changing List Values
Solving Most of the Problem
Exploring a Test Case
The Code
How to Handle the Catch
Exploring a Test Case
More List Operations
Finding the Index of the Maximum
Solving the Problem
Problem #13: Baker Bonus
The Challenge
Input
Output
Representing a Table
Exploring a Test Case
Nested Lists
Solving the Problem
Summary
Chapter Exercises
Notes
6
DESIGNING PROGRAMS WITH FUNCTIONS
Problem #14: Card Game
The Challenge
Input
Output
Exploring a Test Case
Defining and Calling Functions
Functions Without Arguments
Functions with Arguments
Keyword Arguments
Local Variables
Mutable Parameters
Return Values
Function Documentation
Solving the Problem
Problem #15: Action Figures
The Challenge
Input
Output
Representing the Boxes
Top-Down Design
Doing Top-Down Design
The Top Level
Task 1: Read Input
Task 2: Check Whether All Boxes Are OK
Task 3: Obtain a New List of Boxes with Only Left and Right
Heights
Task 4: Sort Boxes
Task 5: Determine Whether Boxes Are Organized
Putting It All Together
Summary
Chapter Exercises
Notes
7
READING AND WRITING FILES
Problem #16: Essay Formatting
The Challenge
Input
Output
Working with Files
Opening a File
Reading from a File
Writing to a File
Solving the Problem
Exploring a Test Case
The Code
Problem #17: Farm Seeding
The Challenge
Input
Output
Exploring a Test Case
Top-Down Design
The Top Level
Task 1: Read Input
Task 2: Identify Cows
Another Random Document on
Scribd Without Any Related Topics
ON PERSONAL IDENTITY
but we would still be our selves, to possess and enjoy all these, or we
would not give a doit for them. But, on this supposition, what in
truth should we be the better for them? It is not we, but another, that
would reap the benefit; and what do we care about that other? In
that case, the present owner might as well continue to enjoy them.
We should not be gainers by the change. If the meanest beggar who
crouches at a palace-gate, and looks up with awe and suppliant fear
to the proud inmate as he passes, could be put in possession of all the
finery, the pomp, the luxury, and wealth that he sees and envies on
the sole condition of getting rid, together with his rags and misery, of
all recollection that there ever was such a wretch as himself, he
would reject the proffered boon with scorn. He might be glad to
change situations; but he would insist on keeping his own thoughts,
to compare notes, and point the transition by the force of contrast.
He would not, on any account, forego his self-congratulation on the
unexpected accession of good fortune, and his escape from past
suffering. All that excites his cupidity, his envy, his repining or
despair, is the alternative of some great good to himself; and if, in
order to attain that object, he is to part with his own existence to take
that of another, he can feel no farther interest in it. This is the
language both of passion and reason.
Here lies ‘the rub that makes calamity of so long life:’ for it is not
barely the apprehension of the ills that ‘in that sleep of death may
come,’ but also our ignorance and indifference to the promised good,
that produces our repugnance and backwardness to quit the present
scene. No man, if he had his choice, would be the angel Gabriel to-
morrow! What is the angel Gabriel to him but a splendid vision? He
might as well have an ambition to be turned into a bright cloud, or a
particular star. The interpretation of which is, he can have no
sympathy with the angel Gabriel. Before he can be transformed into
so bright and ethereal an essence, he must necessarily ‘put off this
mortal coil’—be divested of all his old habits, passions, thoughts, and
feelings—to be endowed with other lofty and beatific attributes, of
which he has no notion; and, therefore, he would rather remain a
little longer in this mansion of clay, which, with all its flaws,
inconveniences, and perplexities, contains all that he has any real
knowledge of, or any affection for. When, indeed, he is about to quit
it in spite of himself, and has no other chance left to escape the
darkness of the tomb, he may then have no objection (making a
virtue of necessity) to put on angels’ wings, to have radiant locks, to
wear a wreath of amaranth, and thus to masquerade it in the skies.
It is an instance of the truth and beauty of the ancient mythology,
that the various transmutations it recounts are never voluntary, or of
favourable omen, but are interposed as a timely release to those who,
driven on by fate, and urged to the last extremity of fear or anguish,
are turned into a flower, a plant, an animal, a star, a precious stone,
or into some object that may inspire pity or mitigate our regret for
their misfortunes. Narcissus was transformed into a flower; Daphne
into a laurel; Arethusa into a fountain (by the favour of the gods)—
but not till no other remedy was left for their despair. It is a sort of
smiling cheat upon death, and graceful compromise with
annihilation. It is better to exist by proxy, in some softened type and
soothing allegory, than not at all—to breathe in a flower or shine in a
constellation, than to be utterly forgot; but no one would change his
natural condition (if he could help it) for that of a bird, an insect, a
beast, or a fish, however delightful their mode of existence, or
however enviable he might deem their lot compared to his own.
Their thoughts are not our thoughts—their happiness is not our
happiness; nor can we enter into it except with a passing smile of
approbation, or as a refinement of fancy. As the poet sings:—
‘What more felicity can fall to creature
Than to enjoy delight with liberty,
And to be lord of all the works of nature?
To reign in the air from earth to highest sky;
To feed on flowers and weeds of glorious feature;
To taste whatever thing doth please the eye?—
Who rests not pleased with such happiness,
Well worthy he to taste of wretchedness!’
But then I could never make up my mind to his preferring Rowe and
Dryden to the worthies of the Elizabethan age; nor could I, in like
manner, forgive Sir Joshua—whom I number among those whose
existence was marked with a white stone, and on whose tomb might
be inscribed ‘Thrice Fortunate!’—his treating Nicholas Poussin with
contempt. Differences in matters of taste and opinion are points of
honour—‘stuff o’ the conscience’—stumbling-blocks not to be got
over. Others, we easily grant, may have more wit, learning,
imagination, riches, strength, beauty, which we should be glad to
borrow of them; but that they have sounder or better views of things,
or that we should act wisely in changing in this respect, is what we
can by no means persuade ourselves. We may not be the lucky
possessors of what is best or most desirable; but our notion of what
is best and most desirable we will give up to no man by choice or
compulsion; and unless others (the greatest wits or brightest
geniuses) can come into our way of thinking, we must humbly beg
leave to remain as we are. A Calvinistic preacher would not
relinquish a single point of faith to be the Pope of Rome; nor would a
strict Unitarian acknowledge the mystery of the Holy Trinity to have
painted Raphael’s Assembly of the Just. In the range of ideal
excellence, we are distracted by variety and repelled by differences:
the imagination is fickle and fastidious, and requires a combination
of all possible qualifications, which never met. Habit alone is blind
and tenacious of the most homely advantages; and after running the
tempting round of nature, fame, and fortune, we wrap ourselves up
in our familiar recollections and humble pretensions—as the lark,
after long fluttering on sunny wing, sinks into its lowly bed!
We can have no very importunate craving, nor very great
confidence, in wishing to change characters, except with those with
whom we are intimately acquainted by their works; and having these
by us (which is all we know or covet in them), what would we have
more? We can have no more of a cat than her skin; nor of an author
than his brains. By becoming Shakspeare in reality, we cut ourselves
out of reading Milton, Pope, Dryden, and a thousand more—all of
whom we have in our possession, enjoy, and are, by turns, in the best
part of them, their thoughts, without any metamorphosis or miracle
at all. What a microcosm is our’s! What a Proteus is the human
mind! All that we know, think of, or can admire, in a manner
becomes ourselves. We are not (the meanest of us) a volume, but a
whole library! In this calculation of problematical contingencies, the
lapse of time makes no difference. One would as soon have been
Raphael as any modern artist. Twenty, thirty, or forty years of
elegant enjoyment and lofty feeling were as great a luxury in the
fifteenth as in the nineteenth century. But Raphael did not live to see
Claude, nor Titian Rembrandt. Those who found arts and sciences
are not witnesses of their accumulated results and benefits; nor in
general do they reap the meed of praise which is their due. We who
come after in some ‘laggard age,’ have more enjoyment of their fame
than they had. Who would have missed the sight of the Louvre in all
its glory to have been one of those whose works enriched it? Would it
not have been giving a certain good for an uncertain advantage? No:
I am as sure (if it is not presumption to say so) of what passed
through Raphael’s mind as of what passes through my own; and I
know the difference between seeing (though even that is a rare
privilege) and producing such perfection. At one time I was so
devoted to Rembrandt, that I think, if the Prince of Darkness had
made me the offer in some rash mood, I should have been tempted to
close with it, and should have become (in happy hour, and in
downright earnest) the great master of light and shade!
I have run myself out of my materials for this Essay, and want a
well-turned sentence or two to conclude with; like Benvenuto Cellini,
who complains that, with all the brass, tin, iron, and lead he could
muster in the house, his statue of Perseus was left imperfect, with a
dent in the heel of it. Once more then—I believe there is one
character that all the world would be glad to change with—which is
that of a favoured rival. Even hatred gives way to envy. We would be
any thing—a toad in a dungeon—to live upon her smile, which is our
all of earthly hope and happiness; nor can we, in our infatuation,
conceive that there is any difference of feeling on the subject, or that
the pressure of her hand is not in itself divine, making those to whom
such bliss is deigned like the Immortal Gods!
APHORISMS ON MAN
I
Servility is a sort of bastard envy. We heap our whole stock of
involuntary adulation on a single prominent figure, to have an excuse
for withdrawing our notice from all other claims (perhaps juster and
more galling ones), and in the hope of sharing a part of the applause
as train-bearers.
II
Admiration is catching by a certain sympathy. The vain admire the
vain; the morose are pleased with the morose; nay, the selfish and
cunning are charmed with the tricks and meanness of which they are
witnesses, and may be in turn the dupes.
III
Vanity is no proof of conceit. A vain man often accepts of praise as
a cheap substitute for his own good opinion. He may think more
highly of another, though he would be wounded to the quick if his
own circle thought so. He knows the worthlessness and hollowness
of the flattery to which he is accustomed, but his ear is tickled with
the sound; and the effeminate in this way can no more live without
the incense of applause, than the effeminate in another can live
without perfumes or any other customary indulgence of the senses.
Such people would rather have the applause of fools than the
approbation of the wise. It is a low and shallow ambition.
IV
It was said of some one who had contrived to make himself
popular abroad by getting into hot water, but who proved very
troublesome and ungrateful when he came home—‘We thought him a
very persecuted man in India’—the proper answer to which is, that
there are some people who are good for nothing else but to be
persecuted. They want some check to keep them in order.
V
It is a sort of gratuitous error in high life, that the poor are
naturally thieves and beggars, just as the latter conceive that the rich
are naturally proud and hard-hearted. Give a man who is starving a
thousand a-year, and he will be no longer under a temptation to get
himself hanged by stealing a leg of mutton for his dinner; he may still
spend it in gaming, drinking, and the other vices of a gentleman, and
not in charity, about which he before made such an outcry.
VI
Do not confer benefits in the expectation of meeting with
gratitude; and do not cease to confer them because you find those
whom you have served ungrateful. Do what you think fit and right to
please yourself; the generosity is not the less real, because it does not
meet with a correspondent return. A man should study to get
through the world as he gets through St. Giles’s—with as little
annoyance and interruption as possible from the shabbiness around
him.
VII
Common-place advisers and men of the world, are always
pestering you to conform to their maxims and modes, just like the
barkers in Monmouth-street, who stop the passengers by entreating
them to turn in and refit at their second-hand repositories.