100% found this document useful (4 votes)
21 views

Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF 2024 Scribd Download

The document promotes seamless ebook downloads across various genres at ebookluna.com, highlighting specific titles such as 'Data Structures & Algorithms in Python' by John Canning and others. It provides links to download multiple ebooks in formats like PDF, ePub, and MOBI, along with a brief overview of the content covered in the featured books. Additionally, it includes acknowledgments and information about the authors and their contributions to the field of data structures and algorithms.

Uploaded by

koknidandzo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
21 views

Data Structures & Algorithms in Python 1st Edition John Canning - eBook PDF 2024 Scribd Download

The document promotes seamless ebook downloads across various genres at ebookluna.com, highlighting specific titles such as 'Data Structures & Algorithms in Python' by John Canning and others. It provides links to download multiple ebooks in formats like PDF, ePub, and MOBI, along with a brief overview of the content covered in the featured books. Additionally, it includes acknowledgments and information about the authors and their contributions to the field of data structures and algorithms.

Uploaded by

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

Experience Seamless Full Ebook Downloads for Every Genre at ebookluna.

com

Data Structures & Algorithms in Python 1st Edition


John Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-
in-python-ebook-pdf/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://ebookluna.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Data Structures & Algorithms in Python 1st Edition John


Canning - eBook PDF

https://ebookluna.com/download/data-structures-algorithms-in-python-
ebook-pdf/

ebookluna.com

Fundamentals Of Python: Data Structures 2nd Edition


Kenneth A. Lambert - eBook PDF

https://ebookluna.com/download/fundamentals-of-python-data-structures-
ebook-pdf/

ebookluna.com

Data Structures - eBook PDF

https://ebookluna.com/download/data-structures-ebook-pdf/

ebookluna.com

(eBook PDF) Data Structures & Algorithm Analysis in C++


4th Edition

https://ebookluna.com/product/ebook-pdf-data-structures-algorithm-
analysis-in-c-4th-edition/

ebookluna.com
Data Structures & Algorithm Analysis in C++ 4th Edition
(eBook PDF)

https://ebookluna.com/product/data-structures-algorithm-analysis-
in-c-4th-edition-ebook-pdf/

ebookluna.com

Introduction to Algorithms for Data Mining and Machine


Learning 1st edition - eBook PDF

https://ebookluna.com/download/introduction-to-algorithms-for-data-
mining-and-machine-learning-ebook-pdf/

ebookluna.com

Machine Learning for Biometrics: Concepts, Algorithms and


Applications (Cognitive Data Science in Sustainable
Computing) 1st Edition - eBook PDF
https://ebookluna.com/download/machine-learning-for-biometrics-
concepts-algorithms-and-applications-cognitive-data-science-in-
sustainable-computing-ebook-pdf/
ebookluna.com

Data Structures and Applications: A Simple and Systematic


Approach 1st edition - eBook PDF

https://ebookluna.com/download/data-structures-and-applications-a-
simple-and-systematic-approach-ebook-pdf/

ebookluna.com

(eBook PDF) Starting Out with Java: From Control


Structures through Data Structures 3rd Edition

https://ebookluna.com/product/ebook-pdf-starting-out-with-java-from-
control-structures-through-data-structures-3rd-edition/

ebookluna.com
Data Structures & Algorithms in Python
Data Structures & Algorithms in
Python

John Canning
Alan Broder
Robert Lafore

Boston • Columbus • New York • San Francisco • Amsterdam • Cape Town


Dubai • London • Madrid • Milan • Munich • Paris • Montreal • Toronto • Delhi • Mexico City
São Paulo • Sidney • Hong Kong • Seoul • Singapore • Taipei • Tokyo
Many of the designations used by manufacturers and sellers to distinguish their products are claimed
as trademarks. Where those designations appear in this book, and the publisher was aware of a
trademark claim, the designations have been printed with initial capital letters or in all capitals.
The authors and publisher have taken care in the preparation of this book, but make no expressed or
implied warranty of any kind and assume no responsibility for errors or omissions. No liability is
assumed for incidental or consequential damages in connection with or arising out of the use of the
information or programs contained herein.
For information about buying this title in bulk quantities, or for special sales opportunities (which
may include electronic versions; custom cover designs; and content particular to your business,
training goals, marketing focus, or branding interests), please contact our corporate sales department
at [email protected] or (800) 382-3419.
For government sales inquiries, please contact [email protected].
For questions about sales outside the U.S., please contact [email protected].
Visit us on the Web: informit.com/aw
Library of Congress Control Number: 2022910068
Copyright © 2023 Pearson Education, Inc.
All rights reserved. Printed in the United States of America. This publication is protected by
copyright, and permission must be obtained from the publisher prior to any prohibited reproduction,
storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,
photocopying, recording, or likewise. For information regarding permissions, request forms and the
appropriate contacts within the Pearson Education Global Rights & Permissions Department, please
visit www.pearsoned.com/permissions/.
ISBN-13: 978-0-13-485568-4
ISBN-10: 0-13-485568-X
ScoutAutomatedPrintCode
Editor-in-Chief
Mark Taub
Director, ITP Product Management
Brett Bartow
Acquisitions Editor
Kim Spenceley
Development Editor
Chris Zahn
Managing Editor
Sandra Schroeder
Project Editor
Mandie Frank
Copy Editor
Chuck Hutchinson
Indexer
Proofreader
Editorial Assistant
Cindy Teeters
Designer
Chuti Prasertsith
Compositor
codeMantra
Pearson’s Commitment to
Diversity, Equity, and Inclusion
Pearson is dedicated to creating bias-free content that reflects the diversity
of all learners. We embrace the many dimensions of diversity, including but
not limited to race, ethnicity, gender, socioeconomic status, ability, age,
sexual orientation, and religious or political beliefs.
Education is a powerful force for equity and change in our world. It has the
potential to deliver opportunities that improve lives and enable economic
mobility. As we work with authors to create content for every product and
service, we acknowledge our responsibility to demonstrate inclusivity and
incorporate diverse scholarship so that everyone can achieve their potential
through learning. As the world’s leading learning company, we have a duty
to help drive change and live up to our purpose to help more people create a
better life for themselves and to create a better world.
Our ambition is to purposefully contribute to a world where
• Everyone has an equitable and lifelong opportunity to succeed
through learning
• Our educational products and services are inclusive and represent the
rich diversity of learners
• Our educational content accurately reflects the histories and
experiences of the learners we serve
• Our educational content prompts deeper discussions with learners and
motivates them to expand their own learning (and worldview)
While we work hard to present unbiased content, we want to hear from you
about any concerns or needs with this Pearson product so that we can
investigate and address them.
Please contact us with concerns about any potential bias at
https://www.pearson.com/report-bias.html.
To my mother, who gave me a thirst for knowledge, to my father, who
taught me the joys of engineering, and to June, who made it possible to
pursue both.

John Canning

For my father Sol Broder, a computer science pioneer, who inspired me to


follow in his footsteps.

To my mother Marilyn Broder, for showing me the satisfaction of teaching


others.

To Fran, for making my life complete.

Alan Broder
Contents
1. Overview

2. Arrays

3. Simple Sorting

4. Stacks and Queues

5. Linked Lists

6. Recursion

7. Advanced Sorting

8. Binary Trees

9. 2-3-4 Trees and External Storage

10. AVL and Red-Black Trees

11. Hash Tables

12. Spatial Data Structures

13. Heaps

14. Graphs

15. Weighted Graphs

16. What to Use and Why


Appendix A. Running the Visualizations

Appendix B. Further Reading

Appendix C. Answers to Questions


Table of Contents
1. Overview
What Are Data Structures and Algorithms?
Overview of Data Structures
Overview of Algorithms
Some Definitions
Programming in Python
Object-Oriented Programming
Summary
Questions
Experiments

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

4. Stacks and Queues


Different Structures for Different Use Cases
Stacks
Queues
Priority Queues
Parsing Arithmetic Expressions
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

9. 2-3-4 Trees and External Storage


ntroduction to 2-3-4 Trees
The Tree234 Visualization Tool
Python Code for a 2-3-4 Tree
Efficiency of 2-3-4 Trees
-3 Trees
External Storage
Summary
Questions
Experiments
Programming Projects

10. AVL and Red-Black Trees


Our Approach to the Discussion
Balanced and Unbalanced Trees
AVL Trees
The Efficiency of AVL Trees
Red-Black Trees
Using the Red-Black Tree Visualization Tool
Experimenting with the Visualization Tool
Rotations in Red-Black Trees
nserting a New Node
Deletion
The Efficiency of Red-Black Trees
-3-4 Trees and Red-Black Trees
Red-Black Tree Implementation
Summary
Questions
Experiments
Programming Projects

11. Hash Tables


ntroduction to Hashing
Open Addressing
Separate Chaining
Hash Functions
Hashing Efficiency
Hashing and External Storage
Summary
Questions
Experiments
Programming Projects

12. Spatial Data Structures


Spatial Data
Computing Distances Between Points
Circles and Bounding Boxes
Searching Spatial Data
Lists of Points
Grids
Quadtrees
Theoretical Performance and Optimizations
Practical Considerations
Further Extensions
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

15. Weighted Graphs


Minimum Spanning Tree with Weighted Graphs
The Shortest-Path Problem
The All-Pairs Shortest-Path Problem
Efficiency
ntractable Problems
Summary
Questions
Experiments
Programming Projects

16. What to Use and Why


Analyzing the Problem
Foundational Data Structures
Special-Ordering Data Structures
Sorting
Specialty Data Structures
External Storage
Onward

Appendix A. Running the Visualizations


For Developers: Running and Changing the Visualizations
For Managers: Downloading and Running the Visualizations
For Others: Viewing the Visualizations on the Internet
Using the Visualizations

Appendix B. Further Reading


Data Structures and Algorithms
Object-Oriented Programming Languages
Object-Oriented Design (OOD) and Software Engineering

Appendix C. Answers to Questions


Chapter 1, “Overview”
Chapter 2, “Arrays”
Chapter 3, “Simple Sorting”
Chapter 4, “Stacks and Queues”
Chapter 5, “Linked Lists”
Chapter 6, “Recursion”
Chapter 7, “Advanced Sorting”
Chapter 8, “Binary Trees”
Chapter 9, “2-3-4 Trees and External Storage”
Chapter 10, “AVL and Red-Black Trees”
Chapter 11, “Hash Tables”
Chapter 12, “Spatial Data Structures”
Chapter 13, “Heaps”
Chapter 14, “Graphs”
Chapter 15, “Weighted Graphs”
Register your copy of Data Structures & Algorithms in Python at
informit.com for convenient access to downloads, updates, and corrections
as they become available. To start the registration process, go to
informit.com/register and log in or create an account. Enter the product
ISBN 9780134855684 and click Submit. Once the process is complete, you
will find any available bonus content under “Registered Products.”
Acknowledgments
From John Canning and Alan Broder
Robert Lafore’s Java-based version of this book has been a mainstay in
Data Structures courses and professionals’ reference shelves around the
world for many years. When Alan’s Data Structures course at Stern College
for Women of Yeshiva University moved on to Python, the inability to use
Lafore’s book in the course was a real loss. We’re thus especially happy to
bring this new and revised edition to the world of Python programmers and
students.
We’d like to thank the many students at Stern who contributed to this book
either directly or indirectly over the past several years. Initial Python
versions of Lafore’s Java implementations were central to Alan’s Python-
based courses, and Stern student feedback helped improve the code’s
clarity, enhanced its performance, and sometimes even identified and fixed
bugs!
For their valuable feedback and recommendations on early drafts of this
new edition, we are grateful to many students in Alan’s Data Structures
courses, including Estee Brooks, Adina Bruce, Julia Chase, Hanna Fischer,
Limor Kohanim, Elisheva Kohn, Shira Orlian, Shira Pahmer, Jennie Peled,
Alexandra Roffe, Avigail Royzenberg, Batia Segal, Penina Waghalter, and
Esther Werblowsky. Our apologies if we’ve omitted anyone’s name.
An open-source package of data structure visualizations is available to
enhance your study of this book, and Stern students played an active role in
the development of the visualization software. John and Alan extend many
thanks to the Stern student pioneers and leaders of this project, including
Ilana Radinsky, Elana Apfelbaum, Ayliana Teitelbaum, and Lily Polonetsky,
as well as the following past and present Stern student contributors: Zoe
Abboudi, Ayelet Aharon, Lara Amar, Natania Birnbaum, Adina Bruce,
Chani Dubin, Sarah Engel, Sarah Graff, Avigayil Helman, Michal
Kaufman, Sarina Kofman, Rachel Leiser, Talia Leitner, Shani Lewis, Rina
Melincoff, Atara Neugroschl, Shira Pahmer, Miriam Rabinovich, Etta Rapp,
Shira Sassoon, Mazal Schoenwald, Shira Schneider, Shira Smith, Riva
Tropp, Alexandra Volchek, and Esther Werblowsky. Our apologies if we
have left anyone off this list.
Many thanks go to Professor David Matuszek of the University of
Pennsylvania for his early contributions of ideas and PowerPoint slides
when Alan first started teaching Data Structures at Stern. Many of the slides
available in the Instructors Resources section have their origin in his clear
and well-designed slides. Also, we are grateful to Professor Marian Gidea
of the Department of Mathematics of Yeshiva University for his insights
into spherical trigonometry.
Finally, we owe a great debt to the talented editors at Pearson who made
this book a reality: Mark Taber, Kim Spenceley, Mandie Frank, and Chris
Zahn. Without their many talents and patient help, this project would just be
an odd collection of text files, drawings, and source code.
From Robert Lafore for the Java-based versions of the book

Acknowledgments to the First Edition


My gratitude for the following people (and many others) cannot be fully
expressed in this short acknowledgment. As always, Mitch Waite had the
Java thing figured out before anyone else. He also let me bounce the applets
off him until they did the job, and extracted the overall form of the project
from a miasma of speculation. My editor, Kurt Stephan, found great
reviewers, made sure everyone was on the same page, kept the ball rolling,
and gently but firmly ensured that I did what I was supposed to do. Harry
Henderson provided a skilled appraisal of the first draft, along with many
valuable suggestions. Richard S. Wright, Jr., as technical editor, corrected
numerous problems with his keen eye for detail. Jaime Niño, Ph.D., of the
University of New Orleans, attempted to save me from myself and
occasionally succeeded, but should bear no responsibility for my approach
or coding details. Susan Walton has been a staunch and much-appreciated
supporter in helping to convey the essence of the project to the
nontechnical. Carmela Carvajal was invaluable in extending our contacts
with the academic world. Dan Scherf not only put the CD-ROM together,
but was tireless in keeping me up to date on rapidly evolving software
changes. Finally, Cecile Kaufman ably shepherded the book through its
transition from the editing to the production process.

Acknowledgments to the Second Edition


My thanks to the following people at Sams Publishing for their competence,
effort, and patience in the development of this second edition. Acquisitions
Editor Carol Ackerman and Development Editor Songlin Qiu ably guided
this edition through the complex production process. Project Editor Matt
Purcell corrected a semi-infinite number of grammatical errors and made
sure everything made sense. Tech Editor Mike Kopak reviewed the
programs and saved me from several problems. Last but not least, Dan
Scherf, an old friend from a previous era, provides skilled management of
my code and applets on the Sams website.
About the Author
Dr. John Canning is an engineer, computer scientist, and researcher. He
earned an S.B. degree in electrical engineering from the Massachusetts
Institute of Technology and a Ph.D. in Computer Science from the
University of Maryland at College Park. His varied professions include
being a professor of computer science, a researcher and software engineer
in industry, and a company vice president. He now is president of
Shakumant Software.
Alan Broder is clinical professor and chair of the Department of Computer
Science at Stern College for Women of Yeshiva University in New York
City. He teaches introductory and advanced courses in Python
programming, data structures, and data science. Before joining Stern
College, he was a software engineer, designing and building large-scale
data analysis systems. He founded and led White Oak Technologies, Inc. as
its CEO, and later served as the chairman and fellow of its successor
company, Novetta, in Fairfax, Virginia.
Introduction
What’s in this book? This book is designed to be a practical introduction to
data structures and algorithms for students who have just begun to write
computer programs. This introduction will tell you more about the book,
how it is organized, what experience we expect readers will have before
starting the book, and what knowledge you will get by reading it and doing
the exercises.

Who This Book Is For


Data structures and algorithms are the core of computer science. If you’ve
ever wanted to understand what computers can do, how they do it, and what
they can’t do, then you need a deep understanding of both (it’s probably
better to say “what computers have difficulty doing” instead of what they
can’t do). This book may be used as a text in a data structures and/or
algorithms course, frequently taught in the second year of a university
computer science curriculum. The text, however, is also designed for
professional programmers, for high school students, and for anyone else
who needs to take the next step up from merely knowing a programming
language. Because it’s easy to understand, it is also appropriate as a
supplemental text to a more formal course. It is loaded with examples,
exercises, and supplemental materials, so it can be used for self-study
outside of a classroom setting.
Our approach in writing this book is to make it easy for readers to
understand how data structures operate and how to apply them in practice.
That’s different from some other texts that emphasize the mathematical
theory, or how those structures are implemented in a particular language or
software library. We’ve selected examples with real-world applications and
avoid using math-only or obscure examples. We use figures and
visualization programs to help communicate key ideas. We still cover the
complexity of the algorithms and the math needed to show how complexity
impacts performance.

What You Need to Know Before You Read This


Book
The prerequisites for using this book are: knowledge of some programming
language and some mathematics. Although the sample code is written in
Python, you don’t need to know Python to follow what’s happening. Python
is not hard to understand, if you’ve done some procedural and/or object-
oriented programming. We’ve kept the syntax in the examples as general as
possible,
More specifically, we use Python version 3 syntax. This version differs
somewhat from Python 2, but not greatly. Python is a rich language with
many built-in data types and libraries that extend its capabilities. Our
examples, however, use the more basic constructs for two reasons: it makes
them easier to understand for programmers familiar with other languages,
and it illustrates the details of the data structures more explicitly. In later
chapters, we do make use of some Python features not found in other
languages such as generators and list comprehensions. We explain what
these are and how they benefit the programmer.
Of course, it will help if you’re already familiar with Python (version 2 or
3). Perhaps you’ve used some of Python’s many data structures and are
curious about how they are implemented. We review Python syntax in
Chapter 1, “Overview,” for those who need an introduction or refresher. If
you’ve programmed in languages like Java, C++, C#, JavaScript, or Perl,
many of the constructs should be familiar. If you’ve only programmed
using functional or domain-specific languages, you may need to spend more
time becoming familiar with basic elements of Python. Beyond this text,
there are many resources available for novice Python programmers,
including many tutorials on the Internet.
Besides a programming language, what should every programmer know? A
good knowledge of math from arithmetic through algebra is essential.
Computer programming is symbol manipulation. Just like algebra, there are
ways of transforming expressions to rearrange terms, put them in different
forms, and make certain parts more prominent, all while preserving the
same meaning. It’s also critical to understand exponentials in math. Much
of computer science is based on knowing what raising one number to a
power of another means. Beyond math, a good sense of organization is also
beneficial for all programming. Knowing how to organize items in different
ways (by time, by function, by size, by complexity, and so on) is crucial to
making programs efficient and maintainable. When we talk about efficiency
and maintainability, they have particular meanings in computer science.
Efficiency is mostly about how much time it takes to compute things but can
also be about the amount of space it takes. Maintainability refers to the ease
of understanding and modifying your programs by other programmers as
well as yourself.
You’ll also need knowledge of how to find things on the Internet, download
and install software, and run them on a computer. The instructions for
downloading and running the visualization programs can be found in
Appendix A of this book. The Internet has made it very easy to access a
cornucopia of tools, including tools for learning programming and
computer science. We expect readers to already know how to find useful
resources and avoid sources that might provide malicious software.

What You Can Learn from This Book


As you might expect from its title, this book can teach you about how data
structures make programs (and programmers) more efficient in their work.
You can learn how data organization and its coupling with appropriate
algorithms greatly affect what can be computed with a given amount of
computing resources. This book can give you a thorough understanding of
how to implement the data structures, and that should enable you to
implement them in any programming language. You can learn the process
of deciding what data structure(s) and algorithms are the most appropriate
to meet a particular programming request. Perhaps most importantly, you
can learn when an algorithm and/or data structure will fail in a given use
case. Understanding data structures and algorithms is the core of computer
science, which is different from being a Python (or other language)
programmer.
The book teaches the fundamental data structures that every programmer
should know. Readers should understand that there are many more. These
basic data structures work in a wide variety of situations. With the skills
you develop in this book, you should be able to read a description of
another data structure or algorithm and begin to analyze whether or not it
will outperform or perform worse than the ones you’ve already learned in
particular use cases.
This book explains some Python syntax and structure, but it will not teach
you all its capabilities. The book uses a subset of Python’s full capabilities
to illustrate how more complex data structures are built from the simpler
constructs. It is not designed to teach the basics of programming to
someone who has never programmed. Python is a very high-level language
with many built-in data structures. Using some of the more primitive types
such as arrays of integers or record structures, as you might find in C or
C++, is somewhat more difficult in Python. Because the book’s focus is the
implementation and analysis of data structures, our examples use
approximations to these primitive types. Some Python programmers may
find these examples unnecessarily complex, knowing about the more
elegant constructs provided with the language in standard libraries. If you
want to understand computer science, and in particular, the complexity of
algorithms, you must understand the underlying operations on the
primitives. When you use a data structure provided in a programming
language or from one of its add-on modules, you will often have to know its
complexity to know whether it will work well for your use case.
Understanding the core data structures, their complexities, and trade-offs
will help you understand the ones built on top of them.
All the data structures are developed using object-oriented programming
(OOP). If that’s a new concept for you, the review in Chapter 1 of how
classes are defined and used in Python provides a basic introduction to
OOP. You should not expect to learn the full power and benefits of OOP
from this text. Instead, you will learn to implement each data structure as a
class. These classes are the types of objects in OOP and make it easier to
develop software that can be reused by many different applications in a
reliable way.
The book uses many examples, but this is not a book about a particular
application area of computer science such as databases, user interfaces, or
artificial intelligence. The examples are chosen to illustrate typical
applications of programs, but all programs are written in a particular
context, and that changes over time. A database program written in 1970
may have appeared very advanced at that time, but it might seem very
trivial today. The examples presented in this text are designed to teach how
data structures are implemented, how they perform, and how to compare
them when designing a new program. The examples should not be taken as
the most comprehensive or best implementation possible of each data
structure, nor as a thorough review of all the potential data structures that
could be appropriate for a particular application area.

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

What Are Data Structures and Algorithms?


Data organizations are ways data is arranged in the computer using its various
storage media (such as random-access memory, or RAM, and disk) and how
that data is interpreted to represent something. Algorithms are the procedures
used to manipulate the data in these structures. The way data is arranged can
simplify the algorithms and make algorithms run faster or slower. Together, the
data organization and the algorithm form a data structure. The data structures
Random documents with unrelated
content Scribd suggests to you:
SALAD OF MIXED SUMMER FRUITS.

Heap a rice-crust-dish quite high with alternate layers of fine fresh


strawberries stripped from the stalks, white and red currants, and
white or red raspberries; strew each layer plentifully with sifted sugar,
and just before the dish is sent to table, pour equally over the top two
wineglassesful of sherry, Madeira, or any other good white wine.
Very thick Devonshire cream may be laid entirely over the fruit,
instead of the wine being mingled with it. Currants by themselves are
excellent prepared in this way, and strawberries also. The fruit
should be gently stirred with a spoon when it is served. Each variety
must be picked with great nicety from the stalks.
PEACH SALAD.

Pare and slice half a dozen fine ripe peaches, arrange them in a
dish, strew them with pounded sugar, and pour over them two or
three glasses of champagne: other wine may be used, but this is
best. Persons who prefer brandy can substitute it for wine. The
quantity of sugar must be proportioned to the sweetness of the fruit.
ORANGE SALAD.

Take off the outer rinds, and then strip away entirely the white
inside skin from some fine China oranges; slice them thin, and
remove the seeds, and thick skin of the cores, as this is done; strew
over them plenty of white sifted sugar, and pour on them a glass or
more of brandy: when the sugar is dissolved serve the oranges. In
France ripe pears of superior quality are sometimes sliced up with
the oranges. Powdered sugar-candy used instead of sugar, is an
improvement to this salad; and the substitution of port, sherry, or
Madeira, for the brandy is often considered so. The fruit may be
used without being pared, and a little curaçao or any other liqueur
may be added to the brandy; or this last, when unmixed, may be
burned after it is poured on the oranges.
TANGERINE ORANGES.

These beautiful little oranges, of which the rinds have a most


peculiar, and to many tastes not a very agreeable flavour, are
remarkably sweet and delicate when in their perfection; but they
come later into the market than the more common varieties of the
orange, and disappear from them sooner. They make a very refined
salad, and also an ornamental rice-crust dish: their cost is somewhat
higher than that of the Malta and St. Michael oranges. There is
another species of this fruit known commonly as the blood-orange
which has many admirers, but it is not we should say greatly superior
to the more abundant kinds usually served at our tables.
PEACHES IN BRANDY.

(Rotterdam Receipt.)

Prepare and stew some fine full-flavoured peaches by the receipt


of page 459, but with two ounces more of sugar to the half pint of
water; when they are tender put them, with their syrup, into glass or
new stone jars, which they should only half fill; and when they are
quite cold pour in white, or very pale, French brandy to within an inch
and a half of the brims: a few peach or apricot kernels can be added
to them. The jars must be corked down.
BRANDIED MORELLA CHERRIES.

Let the cherries be ripe, freshly gathered, and the finest that can
be had; cut off half the length of the stalks, and drop them gently into
clean dry quart bottles with wide necks; leave in each sufficient
space for four ounces of pounded white sugar-candy (or of brown, if
better liked); fill them up entirely with the best French brandy, and
cork them closely: the fruit will not shrivel if thus prepared. A few
cherry, or apricot kernels, or a small portion of cinnamon, can be
added when they are considered an improvement.
BAKED COMPÔTE OF APPLES.

(Our little lady’s receipt.)


Put into a wide Nottingham jar, with a cover, two quarts of golden
pippins, or of the small apple which resembles them in appearance,
called the orange pippin (this is very plentiful in the county of Kent),
pared and cored, but without being divided; strew amongst them
some small strips of very thin fresh lemon-rind, throw on them,
nearly at the top, half a pound of good Lisbon sugar, and set the jar,
with the cover tied on, for some hours, or for a night, into a very slow
oven. The apples will be extremely good, if not too quickly baked:
they should remain entire, but be perfectly tender, and clear in
appearance. Add a little lemon-juice when the season is far
advanced.
Apples, 2 quarts; rind, quite small lemon; sugar, 1/2 lb.: 1 night in
slow oven; or some hours baking in a very gentle one.
Obs.—These apples may be served hot as a second course dish;
or cold, with a boiled custard poured round or over them. They will
likewise answer admirably to fill Gabrielle’s pudding, or a vol-au-vent
à la crême.
DRIED NORFOLK BIFFINS.

The Norfolk biffin is a hard and very red apple, the flesh of the true
kind being partially red as well as the skin. It is most excellent when
carefully dried; and much finer we should say when left more juicy
and but partly flattened, than it is when prepared for sale. Wipe the
apples, arrange them an inch or two apart, and place them in a very
gentle oven until they become so much softened as to yield easily to
sufficient pressure to give them the form of small cakes of less than
an inch thick. They must be set several times into the oven to
produce this effect, as they must be gradually flattened, and must
not be allowed to burst: a cool brick oven is best suited to them.
NORMANDY PIPPINS.

To one pound of the apples, put one quart of water and six ounces
of sugar; let them simmer gently for three hours, or more should they
not be perfectly tender. A few strips of fresh lemon-peel and a very
few cloves are by some persons considered agreeable additions to
the syrup.
Dried Normandy pippins, 1 lb.; water, 1 quart; sugar, 6 oz.; 3 to 4
hours.
Obs.—These pippins, if stewed with care, will be converted into a
rich confection: but they will be very good and more refreshing with
less sugar. They are now exceedingly cheap, and may be converted
into excellent second course dishes at small expense. Half a pound,
as they are light and swell much in the stewing, will be sufficient to
serve at once. Rinse them quickly with cold water, and then soak
them for an hour in the pan in which they are to be stewed, in a quart
of fresh water; place them by the side of the stove to heat gradually,
and when they begin to soften add as much sugar as will sweeten
them to the taste: they require but a small portion. Lemon-rind can
be added to them at pleasure. We have many receipts for other
ways of preparing them, to which we cannot now give place here. It
answers well to bake them slowly in a covered jar. They may be
served hot in a border of rice.
STEWED PRUNEAUX DE TOURS, OR TOURS DRIED PLUMS.

These plums, which resemble in form small dried Norfolk biffins,


make a delicious compôte: they are also excellent served dry. In
France they are stewed until tender in equal parts of water, and of
the light red wine of the country, with about four ounces of sugar to
the pound of fruit: when port wine is used for them a smaller
proportion of it will suffice. The sugar should not be added in stewing
any dried fruits until they are at least half-done, as they will not
soften by any means so easily in syrup as in unsweetened liquid.
Dried plums, 1 lb.; water, 1/2 pint, and light claret, 1/2 pint, or
water, 1/4 pint, and port wine, 1/4 pint: 1-1/2 hour. Sugar, 4 oz.: 2
hours, or more.
Obs.—Common French plums are stewed in the same way with or
without wine. A little experience will teach the cook the exact quantity
of liquid and of sugar which they require.
TO BAKE PEARS.

Wipe some large sound iron pears, arrange them on a dish with
the stalk end upwards, put them into the oven after the bread is
withdrawn, and let them remain all night. If well baked, they will be
excellent, very sweet, and juicy, and much finer in flavour than those
which are stewed or baked with sugar: the bon chrétien pear also is
delicious baked thus.
STEWED PEARS.

Pare, cut in halves, and core a dozen fine pears, put them into a
close shutting stewpan with some thin strips of lemon-rind, half a
pound of sugar in lumps, as much water as will nearly cover them,
and should a very bright colour be desired, a dozen grains of
cochineal, bruised, and tied in a muslin; stew the fruit as gently as
possible, four or five hours, or longer should it not be perfectly
tender. Wine is sometimes added both to stewed pears and to baked
ones. If put into a covered jar, well tied down and baked for some
hours, with a proper quantity of liquid and sugar, they will be very
good.
BOILED CHESTNUTS.

Make a slight incision in the outer skin only, of each chestnut, to


prevent its bursting, and when all are done, throw them into plenty of
boiling water, with about a dessertspoonful of salt to the half gallon.
Some chestnuts will require to be boiled nearly or quite an hour,
others little more than half the time: the cook should try them
occasionally, and as soon as they are soft through, drain them, wipe
them in a coarse cloth, and send them to table quickly in a hot
napkin.
Obs.—The best chestnuts are those which have no internal
divisions: the finest kinds are quite entire when shelled.
ROASTED CHESTNUTS.

The best mode of preparing these is to roast them, as in Spain, in


a coffee-roaster, after having first boiled them from seven to ten
minutes, and wiped them dry. They should not be allowed to cool,
and will require but from ten to fifteen minutes’ roasting. They may,
when more convenient, be finished over the fire as usual, or in a
Dutch or common oven, but in all cases the previous boiling will be
found an improvement. Never omit to cut the rind of each nut slightly
before it is cooked. Serve the chestnuts very hot in a napkin, and
send salt to table with them.
ALMOND SHAMROCKS.

(Very good, and very pretty.)


Whisk the white of a very fresh egg to a froth sufficiently solid to
remain standing in high points when dropped from the whisk; work
into it from half to three-quarters of a pound of very fine dry sifted
sugar, or more should it be needed, to bring the mixture to a
consistency in which it can be worked with the fingers. Have ready
some fine Jordan almonds which have been blanched, and
thoroughly dried at the mouth of the oven; roll each of these in a
small portion of the icing until it is equally covered, and of good form;
then lay them on sheets of thick writing paper, placing three together
in the form of the shamrock, or trefoil, with a small bit of sugar
twisted from the centre almond to form the stalk. When all are ready,
set them into a very slow oven for twenty minutes or longer: they
should become quite firm without taking any colour. They make an
excellent and very ornamental dish. To give them flavour and variety,
use for them sugar which has been rasped on the rinds of some
sound lemons, or Seville oranges, or upon citron, and dried before it
is reduced to powder; or add to the mixture a drop of essence of
roses, and a slight colouring of prepared cochineal. A little spinach-
juice will give a beautiful green tint, but its flavour is not very
agreeable. Filbert or pistachio nuts will answer as well as almonds,
iced in this way.
SMALL SUGAR SOUFFLÉS.

These are made with the same preparation of egg and sugar as
the almond-shamrocks, and may be flavoured and coloured in the
same way. The icing must be sufficiently firm to roll into balls
scarcely larger than a nut: a little sifted sugar should be dusted on
the fingers in making them, but it must not remain on the surface of
the soufflés. They are baked usually in very small round paper
cases, plaited with the edge of a knife, and to give them brilliancy,
the tops are slightly moistened before they are set into the oven, by
passing the finger, or a paste-brush, just dipped in cold water, lightly
over them. Look at them in about a quarter of an hour, and should
they be quite firm to the touch in every part, draw them out; but if not
let them remain longer. They may be baked on sheets of paper, but
will not preserve their form so well.
For 1 white of egg, whisked to a very firm froth, 8 to 10 oz. of sifted
sugar, or more: soufflés, baked in extremely gentle oven, 16 to 30
minutes, or longer if needful.
Obs.—We have confined our receipts here to the most simple
preparations suited to desserts. All the confectionary of the
preceding chapter being appropriate to them (with the exception of
the toffie), as well as various compôtes, clear jellies, and gateaux of
fruit turned from the moulds; and we have already enumerated the
many other dishes of which they may be composed.
ICES.

There is no real difficulty in making ices


for the table; but for want of the proper
means of freezing them, and of preventing
their being acted on by a too warm
atmosphere afterwards, in many houses it
cannot very easily be accomplished unless
the weather be extremely cold.
A vessel called a freezing-pot, an ice-pail,
a strong wooden mallet, and a copper
spatula, or an ice-spoon, are all that is Ice Pail and Freezer.
positively required for this branch of
confectionary. Suitable moulds for iced
puddings, and imitations of fruit, must be had in addition when
needed.
When the composition which is to be frozen is ready, the rough ice
must be beaten quite small with the mallet, and either mingled
quickly with two or three handsful of powdered saltpetre, or used
with a much larger quantity of salt. The freezing-pot must then be
firmly placed in the centre of the ice, which must be pressed closely
into the vacant space around it until it reaches the top. The cover of
the ice-pot, or freezer, may then be removed, and the preparation to
be iced poured into it. It should then be turned by means of the
handle at the top, quickly backwards and forwards for eight or ten
minutes; then the portion which will have frozen to the inside must be
scraped well from it with the ice-spoon and mingled with the
remainder: without this the mass would be full of lumps instead of
being perfectly smooth as it ought to be. The same process must be
continued until the whole of its contents are uniformly frozen.
The water-ices which are made in such perfection on the
continent, are incomparably superior to the ice-creams, and other
sweet compositions which are usually served in preference to them
here. One or two receipts which we append will serve as guides for
many others, which may easily be compounded with any variety of
fresh summer fruit.[179]
179. The ices for desserts should be moulded in the form of fruit or other shapes
adapted to the purpose; the natural flavour and colouring are then given to
the former, but it is only experienced cooks or confectioners generally who
understand this branch of ice-making, and it is better left to them. All the
necessary moulds may be procured at any good ironmongers, where the
manner of using them would be explained: we can give no more space to the
subject.
Red Currant Ice.—Strip from the stalks and take two pounds
weight of fine ripe currants and half a pound of raspberries; rub them
through a fine sieve, and mingle thoroughly with them sufficient cold
syrup to render the mixture agreeably sweet, and,—unless the pure
flavour of the fruit be altogether preferred,—add the strained juice of
one large or of two small lemons, and proceed at once to freeze the
mixture as above. Currants, 2 lbs.; raspberries, 1/2 lb.; sugar, 3/4 to
1 lb.; boiled for 6 or 8 minutes in 1/2 pint of water and left till quite
cold. (Juice of lemon or lemons at pleasure.)
Strawberry and raspberry water-ices are made in precisely the
same manner.
To convert any of these into English ice-creams, merely mingle the
juice and pulp of the fruit with sufficient pounded sugar to sweeten
them, or with the syrup as above, and then blend with them gradually
from a pint and a half to a quart of fresh sweet cream, and the
lemon-juice or not at choice. The Queen’s Custard, the Currant, and
the Quince or Apple Custard of pages 481 and 482 may all be
converted into good ices with a little addition of cream and sugar;
and so likewise may the Countess Cream of page 472, and the
Bavarian Cream of page 477, by omitting the isinglass from either of
them.
CHAPTER XXIX.

Syrups, Liqueurs, &c.

Antique Wine Vase.


Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like