Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF download
Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF download
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/
https://ebooksecure.com/download/data-structures-algorithms-in-
python-ebook-pdf/
https://ebooksecure.com/download/fundamentals-of-python-data-
structures-ebook-pdf/
https://ebooksecure.com/download/data-structures-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-data-structures-
algorithm-analysis-in-c-4th-edition/
Data Structures & Algorithm Analysis in C++ 4th Edition
(eBook PDF)
http://ebooksecure.com/product/data-structures-algorithm-
analysis-in-c-4th-edition-ebook-pdf/
https://ebooksecure.com/download/introduction-to-algorithms-for-
data-mining-and-machine-learning-ebook-pdf/
https://ebooksecure.com/download/machine-learning-for-biometrics-
concepts-algorithms-and-applications-cognitive-data-science-in-
sustainable-computing-ebook-pdf/
https://ebooksecure.com/download/data-structures-and-
applications-a-simple-and-systematic-approach-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-starting-out-with-java-
from-control-structures-through-data-structures-3rd-edition/
Data Structures & Algorithms in Python
Data Structures & Algorithms in
Python
John Canning
Alan Broder
Robert Lafore
John Canning
Alan Broder
Contents
1. Overview
2. Arrays
3. Simple Sorting
5. Linked Lists
6. Recursion
7. Advanced Sorting
8. Binary Trees
13. Heaps
14. Graphs
2. Arrays
The Array Visualization Tool
Using Python Lists to Implement the Array Class
The Ordered Array Visualization Tool
Python Code for an Ordered Array Class
Logarithms
Storing Objects
Big O Notation
Why Not Use Arrays for Everything?
Summary
Questions
Experiments
Programming Projects
3. Simple Sorting
How Would You Do It?
Bubble Sort
Selection Sort
nsertion Sort
Comparing the Simple Sorts
Summary
Questions
Experiments
Programming Projects
5. Linked Lists
Links
The Linked List Visualization Tool
A Simple Linked List
Linked List Efficiency
Abstract Data Types and Objects
Ordered Lists
Doubly Linked Lists
Circular Lists
terators
Summary
Questions
Experiments
Programming Projects
6. Recursion
Triangular Numbers
Factorials
Anagrams
A Recursive Binary Search
The Tower of Hanoi
Sorting with mergesort
Eliminating Recursion
Some Interesting Recursive Applications
Summary
Questions
Experiments
Programming Projects
7. Advanced Sorting
Shellsort
Partitioning
Quicksort
Degenerates to O(N2) Performance
Radix Sort
Timsort
Summary
Questions
Experiments
Programming Projects
8. Binary Trees
Why Use Binary Trees?
Tree Terminology
An Analogy
How Do Binary Search Trees Work?
Finding a Node
nserting a Node
Traversing the Tree
Finding Minimum and Maximum Key Values
Deleting a Node
The Efficiency of Binary Search Trees
Trees Represented as Arrays
Printing Trees
Duplicate Keys
The BinarySearchTreeTester.py Program
The Huffman Code
Summary
Questions
Experiments
Programming Projects
13. Heaps
ntroduction to Heaps
The Heap Visualization Tool
Python Code for Heaps
A Tree-Based Heap
Heapsort
Order Statistics
Summary
Questions
Experiments
Programming Projects
14. Graphs
ntroduction to Graphs
Traversal and Search
Minimum Spanning Trees
Topological Sorting
Connectivity in Directed Graphs
Summary
Questions
Experiments
Programming Projects
Structure
Each chapter presents a particular group of data structures and associated
algorithms. At the end of the chapters, we provide review questions
covering the key points in the chapter and sometimes relationships to
previous chapters. The answers for these can be found in Appendix C,
“Answers to Questions.” These questions are intended as a self-test for
readers, to ensure you understood all the material.
Many chapters suggest experiments for readers to try. These can be
individual thought experiments, team assignments, or exercises with the
software tools provided with the book. These are designed to apply the
knowledge just learned to some other area and help deepen your
understanding.
Programming projects are longer, more challenging programming exercises.
We provide a range of projects of different levels of difficulty. These
projects might be used in classroom settings as homework assignments.
Sample solutions to the programming projects are available to qualified
instructors from the publisher.
History
Mitchell Waite and Robert Lafore developed the first version of this book
and titled it Data Structures and Algorithms in Java. The first edition was
published in 1998, and the second edition, by Robert, came out in 2002.
John Canning and Alan Broder developed this version using Python due to
its popularity in education and commercial and noncommercial software
development. Java is widely used and an important language for computer
scientists to know. With many schools adopting Python as a first
programming language, the need for textbooks that introduce new concepts
in an already familiar language drove the development of this book. We
expanded the coverage of data structures and updated many of the
examples.
We’ve tried to make the learning process as painless as possible. We hope
this text makes the core, and frankly, the beauty of computer science
accessible to all. Beyond just understanding, we hope you find learning
these ideas fun. Enjoy yourself!
1. Overview
You have written some programs and learned enough to think that
programming is fun, or at least interesting. Some parts are easy, and some parts
are hard. You’d like to know more about how to make the process easier, get
past the hard parts, and conquer more complex tasks. You are starting to study
the heart of computer science, and that brings up many questions. This chapter
sets the stage for learning how to make programs that work properly and fast. It
explains a bunch of new terms and fills in background about the programming
language that we use in the examples.
In This Chapter
• What Are Data Structures and Algorithms?
• Overview of Data Structures
• Overview of Algorithms
• Some Definitions
• Programming in Python
• Object-Oriented Programming
——
CHAPTER II.
The deepest ice that ever froze
Can only o’er the surface close;
The living stream lies quick below,
And flows, and cannot cease to flow.
Byron.
——
CHAPTER III.
They were met, as the rock meets the wave,
And dashes its fury to air;
They were met, as the foe should be met by the brave,
With hearts for the conflict, but not for despair.
Whilst the captain, mate and steward, were making their brief
preparation for a most hazardous undertaking, the men of the
Josephine, with that promptness and resolution so common amongst
seamen when they think at all, had determined upon the course
they would adopt in the impending struggle.
Although the numerical discrepancy between the two parties
seemed so great, the actual difference in their relative strength was
not so considerable as it appeared. The sailors, it is true, had the
physical force—they were five to one; but the captain’s small band
felt more confidence from the moral influence that they knew was
on their side, than if their numbers had been trebled, without it.
Habit ever exercises a controlling influence, unless overcome by
some powerful exciting principle, and men never fly in the face of
authority to which they have always been accustomed to yield
implicit obedience, but from one of two causes—either a hasty
impulse, conceived in a moment, and abandoned by actors
frightened at their own audacity; or, a sense of wrong and injustice
so keen and poignant, as to make death preferable to further
submission.
Aware of custom’s nearly invincible power, having often seen
seamen rebel, and then at the first warning gladly skulk back to their
duty, the captain unhesitatingly advanced up the weather-gangway
to the break of the forecastle, and confronted his mutinous crew.
The men, who were huddled around the end of the windlass, some
sitting, others standing, talking together in low tones, only showed
they were aware of the captain’s presence by suddenly ceasing their
conversation—but not a man of them moved.
Captain Andrews, though quick tempered, was a man of
judgment and experience; and he saw by the calmness and
quietness of his men, that their insubordination was the result of
premeditation—a thing he had not before thought—and he became
aware of the difficulties of his position. He could not, for his life,
think of yielding; to give up to a sailor would, in his estimation, be
the deepest degradation. And moral influence was all he could rely
upon with which to compel obedience—feeling that if an actual strife
commenced, it could but result in his discomfiture. His tone,
therefore, was low and determined, as with cocked pistol in hand he
addressed his crew:
“Men, do you know that you are, every one of you, guilty of
mutiny? Do you know that the punishment for mutiny on the high
seas is death? Do you know this? Have you thought of it?” Here the
captain paused for an instant, as if waiting for a reply; and a voice
from the group around the windlass answered—
“We have!”
Rather surprised at the boldness of the reply, but still retaining
his presence of mind, the captain continued:
“What is it then that has induced you to brave this penalty? Have
you been maltreated? Do you not have plenty of provisions? Your
regular watches below? Step out, one of you, and state your
grievances. You know I am not a tyrant, and I wish from you nothing
more than you promised in the shipping articles!”
At this call, the eyes of the men were all turned toward Wilson,
the boatswain, who, seeing it was expected from him, stepped out
to act as spokesman. Respectfully touching his tarpaulin, he waited
for the captain to question him. Observing this, the captain said,
“Well, Wilson, your messmates have put you forth as their
speaker; and it strikes me that you are the ringleader of this
misguided movement. I am certain you have sense enough to
understand the risk you are running, and desire you to inform me
what great wrong it is that you complain of. For assuredly you must
feel grievously imposed upon, to make you all so far forget what is
due to yourselves as seamen, to me as your captain, and to the laws
of your country!”
“I ain’t much of a yarn-spinner, Captain Andrews, and I can turn
in the plies of a splice smoother and more ship-shape than the ends
of a speech; and it may be as how I’ll ruffle your temper more nor it
is now, by what I have to say—” commenced the boatswain.
“Never mind my temper, sir,” interrupted the captain, “proceed!”
“We all get plenty of grub, Captain Andrews, and that of the
best,” continued Wilson; his equanimity not in the least disturbed by
the skipper’s interruption. “We have our regular watches, and don’t
complain of our work, for we shipped as seamen, and can all do
seamen’s duty. But sailors have feelings, Captain Andrews, though
they are not often treated as if they had; and it hurts us worse to
see those worked double-tides who can’t take their own part, than if
we were mistreated ourselves; and to come to the short of it, all this
row’s about little Tom, there, and nothing else.”
“Is he not treated just as well as the rest of you? Has he not the
same quarters, and the same rations, that the men are content
with? Who works him double-tides?” answered the captain, his
anger evidently increasing at the mention of Tom’s name; and the
effort to restrain himself, being almost too great for the choleric
officer to compass.
“You can’t beat to wind’ard against a head-sea, Captain Andrews,
without a ship’s pitching, no more than you can reef a to’s-sail
without going aloft.” Wilson went on without change in manner,
though his voice became more concise and firm in its tone. “And I
can’t tell you, like some of them shore chaps, what you don’t want
to hear, without heaving you aback. We ain’t got any thing agin you,
if you was let alone; all we wants is for you to give your own orders,
and to keep Mrs. Andrews from bedeviling Tom. The boy’s as good a
boy as ever furled a royal, and never skulks below when he’s wanted
on deck; but he stands his regular watches, and then, when he
ought to sleep, he’s everlastingly kept in the cabin, and whipped and
knocked about for the amusement of young master, and that’s just
the whole of it. We’ve stood it long enough, and wont return to duty
until you promise—”
“Silence, sir!” roared the captain, perfectly furious, and unable
longer to remain quiet. “Not another word! I’ve listened to insolence
too long by half, already! Now, sir, I have a word to say to you, and
mind you heed it. Walk aft to the quarter-deck!”
The boatswain, though he heard the order plainly, and
understood it clearly, paid no attention to it.
“Do you hear me, sir?” asked the captain. “I give you whilst I
count ten, to start. I do not wish to shoot you, Wilson; but if you do
not move before I count ten, I’ll drive this ball through you—as I
hope to reach port, I will!”
Raising his pistol until it covered the boatswain’s breast, the
captain commenced counting in a clear and audible tone. Intense
excitement was depicted on the faces of the men; and some anxiety
was shown by the quick glances cast by the chief mate and steward,
first at the captain, and then at the crew. Wilson, with his eyes fixed
in the captain’s face, and his arms loosely folded across his breast,
stood perfectly quiet, as if he were an indifferent spectator.
“Eight! Nine!” said the captain, “there is but one left, Wilson; with
it I fire if you do not start.”
The boatswain remained motionless. “Te—” escaped the
commander’s lips; and as it did, the sharp edge of Wilson’s heavy
tarpaulin hat struck him a severe blow in the face. This was so
entirely unexpected, that the captain involuntarily threw back his
head, and by the same motion, without intending it, threw up his
arm and clenched his hand enough to fire off the pistol held in it;
the ball from which went through the flying-jib, full twenty feet
above Wilson’s head.
The charm that had held the men in check, was broken by the
first movement toward action, and they made a rush toward the
captain and his two supporters. Bravely, though, they stood their
ground; and Frank Adams, the sailor introduced with Tom in the
forecastle, received the ball from the mate’s pistol in the fleshy part
of his shoulder, as he was about to strike that worthy with a
handspike. Gallantly assisted by the steward, the captain and mate
made as much resistance as three men could against fifteen. The
odds were, however, too great; spite of their bravery, the three were
soon overpowered and the contest was nearly ended, when a
temporary change was made in favor of the weaker party by the
appearance in the fray of the second mate. He, during the whole
colloquy, had been at the wheel, forgotten by both parties. His
sudden arrival, therefore, as with lusty blows he laid about him,
astonished the seamen, who gave back for an instant, and allowed
their opponents to regain their feet. They did not allow them much
time, however, to profit by this respite, for in a few seconds,
understanding the source from whence assistance had come, they
renewed the attack with increased vigor, and soon again obtained
the mastery. But it was no easy matter to confine the three officers
and the steward, who resisted with their every power, particularly as
the men were anxious to do them no more bodily injury than they
were compelled to, in effecting their purpose.
So absorbed were all hands in the strife in which they were
engaged, that not one of them noticed the fact that what had been
the weather-side of the barque at the commencement of the affray,
was now the lee; nor did any of the men—all seamen as they were—
observe that the vessel was heeling over tremendously, her lee-
scuppers nearly level with the water. A report, loud as a cannon,
high in the air, first startled the combatants; then, with a rushing
sound, three large, heavy bodies, fell from aloft, one of which
striking the deck near the combatants, threatened all with instant
destruction, whilst the other two fell with a loud splash into the sea
to leeward.
In the new danger, both the victors and vanquished were equally
interested, and at the same instant looked aloft to discover the
cause. The first glance convinced every one of the necessity for
prompt and vigorous action. Their position was, indeed, one fraught
with imminent danger. Left without a helmsman, by the second mate
going to the assistance of the captain, the barque, close-hauled with
a stiff breeze blowing, had come up in the wind, and was now flat
aback; that is, the wind, instead of blowing against the sails from
behind, was before them. The fore and main-royal, and top-gallant
masts, with all their gear, had been carried away; and the ship was
gathering stern-way at a rate that would soon run her under.
The natural desire for self-preservation, combined with the
instincts and habits of both officers and men to cause them entirely
to forget the fierce contest in which they had just been engaged—
their thoughts were changed from each other, to the ship and its
situation—and the officers were at once permitted to regain their
feet.
No sooner did Captain Andrews find himself at liberty, than he at
once assumed command, and issued his orders as loud and clear as
if nothing had interrupted his authority.
“To the wheel! to the wheel! Mr. Hart! All hands ware ship!” were
his first words; and the men with alacrity hurried to their stations,
whilst the mate ran to the helm.
The captain’s wife and son had been in the cabin, anxiously
awaiting the result of the controversy on the forecastle, but alarmed
by the failing spars, they had hurried on deck and were now on the
poop. In the hurry and confusion consequent upon the ship’s
hazardous position, all hands were so busy that no one paid
attention to Charles and Mrs. Andrews; and they were too much
alarmed to take due care of themselves, else would they have
sought a less exposed situation. As the spanker jibed, Charles was
standing nearly amidships on the deck, and before he even had time
to shriek, the boom struck him and hurled him over the monkey-rail
into the sea. His mother, who was close to the mizzen-mast, saw
him just as he went over, and terror-stricken, sunk to the deck in a
swoon, without uttering a sound. Unable to swim, a puny child in the
angry waves of the rough Atlantic, the case of Charles seemed a
hopeless one; but rescue came from a source he could have least
expected. Tom, the sailor-boy, who was on the tafferel belaying the
spanker-sheet to windward, recognized the captain’s son as he
floated clear of the stern; and actuated by that generous, gallant
spirit that had so endeared him to his messmates, he shouted to the
mate that Charles was over-board! and fearlessly sprang into the sea
to his assistance. Tom was an excellent swimmer, and he found no
difficulty in supporting Charles’ delicate form until the barque hove
round, when they were both picked up and taken on board.
The joy of the mother at having restored to her the idol of her
heart; the grateful feelings she and the father felt toward the
deliverer of their child, we will not attempt to describe; only the
results will we give of this heroic action. Tom was treated by the
captain as a son; the crew were forgiven for their mutinous conduct,
and cheerfully returned to duty; and Tom, now a distinguished naval
officer, dates his first step upon the ladder that leads to eminence,
from the day he so narrowly escaped a severe whipping.
Laurensville, South Carolina.
———
BY WILLIAM CULLEN BRYANT.
———
Rein in thy snorting charger!
That stag but cheats thy sight;
He is luring thee on to Windeck,
With his seeming fear and flight.
JENNY LIND.
———
BY HENRY T. TUCKERMAN.
———
[WITH A PORTRAIT.]