100% found this document useful (2 votes)
49 views

A Common Sense Guide to Data Structures and Algorithms in Python Volume 1 Level Up Your Core Programming Skills Jay Wengrow all chapter instant download

The document promotes 'A Common Sense Guide to Data Structures and Algorithms in Python Volume 1' by Jay Wengrow, which aims to simplify the understanding of data structures and algorithms for programmers. It emphasizes the importance of these concepts in writing efficient code and provides various resources and exercises for practical learning. Additionally, it offers links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

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

A Common Sense Guide to Data Structures and Algorithms in Python Volume 1 Level Up Your Core Programming Skills Jay Wengrow all chapter instant download

The document promotes 'A Common Sense Guide to Data Structures and Algorithms in Python Volume 1' by Jay Wengrow, which aims to simplify the understanding of data structures and algorithms for programmers. It emphasizes the importance of these concepts in writing efficient code and provides various resources and exercises for practical learning. Additionally, it offers links to download the book and other related ebooks from ebookfinal.com.

Uploaded by

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

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

A Common Sense Guide to Data Structures and


Algorithms in Python Volume 1 Level Up Your Core
Programming Skills Jay Wengrow

_____ Click the link below to download _____


https://ebookfinal.com/download/a-common-sense-guide-
to-data-structures-and-algorithms-in-python-
volume-1-level-up-your-core-programming-skills-jay-
wengrow/

Explore and download more ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Problem Solving in Data Structures Algorithms Using Python


Programming Interview Guide 1st Edition Hemant Jain

https://ebookfinal.com/download/problem-solving-in-data-structures-
algorithms-using-python-programming-interview-guide-1st-edition-
hemant-jain/

Data structures and algorithms in Java 2nd Edition Adam


Drozdek

https://ebookfinal.com/download/data-structures-and-algorithms-in-
java-2nd-edition-adam-drozdek/

Algorithms and Theory of Computation Handbook Second


Edition Volume 1 General Concepts and Techniques Chapman
Hall CRC Applied Algorithms and Data Structures series
Mikhail J. Atallah
https://ebookfinal.com/download/algorithms-and-theory-of-computation-
handbook-second-edition-volume-1-general-concepts-and-techniques-
chapman-hall-crc-applied-algorithms-and-data-structures-series-
mikhail-j-atallah/

Lining Up Data in ArcGIS A Guide to Map Projections 2nd


Edition Maher

https://ebookfinal.com/download/lining-up-data-in-arcgis-a-guide-to-
map-projections-2nd-edition-maher/
Five Dimensions of Quality A Common Sense Guide to
Accreditation and Accountability 1st Edition Linda Suskie

https://ebookfinal.com/download/five-dimensions-of-quality-a-common-
sense-guide-to-accreditation-and-accountability-1st-edition-linda-
suskie/

Introduction to Computation and Programming Using Python


with Application to Understanding Data 2nd edition Edition
Guttag
https://ebookfinal.com/download/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-2nd-
edition-edition-guttag/

Head First Programming A Learner s Guide to Programming


Using the Python Language 1st Edition David Griffiths

https://ebookfinal.com/download/head-first-programming-a-learner-s-
guide-to-programming-using-the-python-language-1st-edition-david-
griffiths/

Common Core Curriculum English Grades 9 12 2nd Edition


Common Core

https://ebookfinal.com/download/common-core-curriculum-english-
grades-9-12-2nd-edition-common-core/

Fundamentals of Python From First Programs through Data


Structures 1st Edition Kenneth A. Lambert

https://ebookfinal.com/download/fundamentals-of-python-from-first-
programs-through-data-structures-1st-edition-kenneth-a-lambert/
A Common Sense Guide to Data Structures and
Algorithms in Python Volume 1 Level Up Your Core
Programming Skills Jay Wengrow Digital Instant
Download
Author(s): Jay Wengrow
ISBN(s): 9798888650356, 8888650350
Edition: P1.0
File Details: PDF, 17.44 MB
Year: 2023
Language: english
A Common-Sense
Guide to Data
Structures and
Algorithms in
Python, Volume 1
Level Up Your Core Programming
Skills

by Jay Wengrow

Version: P1.0 (December 2023)


Copyright © 2023 The Pragmatic Programmers, LLC. This book is licensed to the
individual who purchased it. We don't copy-protect it because that would limit your
ability to use it for your own purposes. Please don't break this trust—you can use
this across all of your devices but please do not share this copy with other
members of your team, with friends, or via file sharing services. Thanks.

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 Pragmatic Programmers, LLC was aware of a trademark claim, the
designations have been printed in initial capital letters or in all capitals. The
Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming,
Pragmatic Bookshelf and the linking g device are trademarks of The Pragmatic
Programmers, LLC.

Every precaution was taken in the preparation of this book. However, the publisher
assumes no responsibility for errors or omissions, or for damages that may result
from the use of information (including program listings) contained herein.

About the Pragmatic Bookshelf


The Pragmatic Bookshelf is an agile publishing company. We’re here because we
want to improve the lives of developers. We do this by creating timely, practical
titles, written by programmers for programmers.

Our Pragmatic courses, workshops, and other products can help you and your
team create better software and have more fun. For more information, as well as
the latest Pragmatic titles, please visit us at http://pragprog.com.

Our ebooks do not contain any Digital Restrictions Management, and have always
been DRM-free. We pioneered the beta book concept, where you can purchase and
read a book while it’s still being written, and provide feedback to the author to
help make a better book for everyone. Free resources for all purchasers include
source code downloads (if applicable), errata and discussion forums, all available
on the book's home page at pragprog.com. We’re here to make your life easier.

New Book Announcements


Want to keep up on our latest titles and announcements, and occasional special
offers? Just create an account on pragprog.com (an email address and a password
is all it takes) and select the checkbox to receive newsletters. You can also follow
us on twitter as @pragprog.

About Ebook Formats


If you buy directly from pragprog.com, you get ebooks in all available formats for
one price. You can synch your ebooks amongst all your devices (including
iPhone/iPad, Android, laptops, etc.) via Dropbox. You get free updates for the life of
the edition. And, of course, you can always come back and re-download your books
when needed. Ebooks bought from the Amazon Kindle store are subject to
Amazon's polices. Limitations in Amazon's file format may cause ebooks to display
differently on different devices. For more information, please see our FAQ at
pragprog.com/#about-ebooks. To learn more about this book and access the free
resources, go to https://pragprog.com/book/jwpython, the book's homepage.

Thanks for your continued support,

The Pragmatic Bookshelf

The team that produced this book includes: Dave Thomas (Publisher),
Janet Furlow (COO), Tammy Coron (Managing Editor),
Katharine Dvorak (Development Editor), L. Sakhi MacMillan (Copy Editor),
Potomac Indexing, LLC (Indexing), Gilson Graphics (Layout)

For customer support, please contact [email protected].

For international rights, please contact [email protected].


Table of Contents

Preface
Who Is This Book For?
The Python Edition
A Note About the Code
What’s in This Book?
How to Read This Book
Online Resources
Connecting

Acknowledgments

1. Why Data Structures Matter


Data Structures
The Array: The Foundational Data Structure
Measuring Speed
Reading
Searching
Insertion
Deletion
Sets: How a Single Rule Can Affect Efficiency
Wrapping Up
Exercises
2. Why Algorithms Matter
Ordered Arrays
Searching an Ordered Array
Binary Search
Binary Search vs. Linear Search
Wrapping Up
Exercises

3. O Yes! Big O Notation


Big O: How Many Steps Relative to N Elements?
The Soul of Big O
An Algorithm of the Third Kind
Logarithms
O(log N) Explained
Practical Examples
Wrapping Up
Exercises

4. Speeding Up Your Code with Big O


Bubble Sort
Bubble Sort in Action
The Efficiency of Bubble Sort
A Quadratic Problem
A Linear Solution
Wrapping Up
Exercises
5. Optimizing Code With and Without Big O
Selection Sort
Selection Sort in Action
The Efficiency of Selection Sort
Ignoring Constants
Big O Categories
Wrapping Up
Exercises

6. Optimizing for Optimistic Scenarios


Insertion Sort
Insertion Sort in Action
The Efficiency of Insertion Sort
The Average Case
A Practical Example
Wrapping Up
Exercises

7. Big O in Everyday Code


Mean Average of Even Numbers
Word Builder
Array Sample
Average Celsius Reading
Clothing Labels
Count the Ones
Palindrome Checker
Get All the Products
Password Cracker
Wrapping Up
Exercises

8. Blazing Fast Lookup with Hash Tables


Hash Tables
Hashing with Hash Functions
Building a Thesaurus for Fun and Profit, but Mainly
Profit
Hash Table Lookups
Dealing with Collisions
Making an Efficient Hash Table
Hash Tables for Organization
Hash Tables for Speed
Wrapping Up
Exercises

9. Crafting Elegant Code with Stacks and


Queues
Stacks
Abstract Data Types
Stacks in Action
The Importance of Constrained Data Structures
Queues
Queues in Action
Wrapping Up
Exercises
10. Recursively Recurse with Recursion
Recurse Instead of Loop
The Base Case
Reading Recursive Code
Recursion in the Eyes of the Computer
Filesystem Traversal
Wrapping Up
Exercises

11. Learning to Write in Recursive


Recursive Category: Repeatedly Execute
Recursive Category: Calculations
Top-Down Recursion: A New Way of Thinking
The Staircase Problem
Anagram Generation
Wrapping Up
Exercises

12. Dynamic Programming


Unnecessary Recursive Calls
The Little Fix for Big O
The Efficiency of Recursion
Overlapping Subproblems
Dynamic Programming Through Memoization
Dynamic Programming Through Going Bottom-Up
Wrapping Up
Exercises
13. Recursive Algorithms for Speed
Partitioning
Quicksort
The Efficiency of Quicksort
Quicksort in the Worst-Case Scenario
Quickselect
Sorting as a Key to Other Algorithms
Wrapping Up
Exercises

14. Node-Based Data Structures


Linked Lists
Implementing a Linked List
Reading
Searching
Insertion
Deletion
Efficiency of Linked List Operations
Linked Lists in Action
Doubly Linked Lists
Queues as Doubly Linked Lists
Wrapping Up
Exercises

15. Speeding Up All the Things with Binary


Search Trees
Trees
Binary Search Trees
Searching
Insertion
Deletion
Binary Search Trees in Action
Binary Search Tree Traversal
Wrapping Up
Exercises

16. Keeping Your Priorities Straight with Heaps


Priority Queues
Heaps
Heap Properties
Heap Insertion
Looking for the Last Node
Heap Deletion
Heaps vs. Ordered Arrays
The Problem of the Last Node…Again
Arrays as Heaps
Heaps as Priority Queues
Wrapping Up
Exercises

17. It Doesn’t Hurt to Trie


Tries
Storing Words
Trie Search
The Efficiency of Trie Search
Trie Insertion
Building Autocomplete
Completing Autocomplete
Tries with Values: A Better Autocomplete
Wrapping Up
Exercises

18. Connecting Everything with Graphs


Graphs
Directed Graphs
Object-Oriented Graph Implementation
Graph Search
Depth-First Search
Breadth-First Search
The Efficiency of Graph Search
Weighted Graphs
Dijkstra’s Algorithm
Wrapping Up
Exercises

19. Dealing with Space Constraints


Big O of Space Complexity
Trade-Offs Between Time and Space
The Hidden Cost of Recursion
Wrapping Up
Exercises
20. Techniques for Code Optimization
Prerequisite: Determine Your Current Big O
Start Here: The Best-Imaginable Big O
Magical Lookups
Recognizing Patterns
Greedy Algorithms
Change the Data Structure
Wrapping Up
Parting Thoughts
Exercises

A1. Exercise Solutions


Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Chapter 15
Chapter 16
Chapter 17
Chapter 18
Chapter 19
Chapter 20

Copyright © 2024, The Pragmatic Bookshelf.


Early Praise for A
Common-Sense Guide to
Data Structures and
Algorithms in Python,
Volume 1
Students and programmers everywhere are told how
important algorithms and data structures are for
creating quality software—not to mention getting hired
at the best companies—and, yet, there are so few
resources that bring actual clarity to the topic. This book
does! The combination of Python’s simplicity and Jay’s
ability to drill down on what you need to know is a
winning formula. Reading this book is a worthwhile
investment for any software engineer.

→ Lyndon Purcell
Software Developer, OK200
A Common Sense Guide to Data Structures and
Algorithms in Python is one of those rare books that
both unravels the sometimes impenetrable algorithmic
content and keeps the reader engaged with a direct and
approachable writing style. I highly recommend this
book to anyone that wants to dig into algorithms to
improve their programming skills.

→ Terry Peppers
Vice President of Engineering, LogicGate
As a beginner to coding, I have read many books on
algorithms and Jay’s book is the only one which doesn’t
assume the reader is a math genius nor does it treat
you in a condescending manner. From the start of the
book he encourages your learning and understanding as
a mentor and a friend.

→ Katy Douglas
Student, The Open University
The book serves as an exceptional reference for
individuals seeking to grasp the fundamental concepts
in data structures and algorithms (DSA) and an ideal
entry point to the realm of DSA, particularly for those
with limited or no prior background in computer science.
It excels in explaining the complex algorithms by using
clever illustrations and examples, making the book a
fascinating read.

→ Ahmad Shahba
Lead Software Engineer, Science Systems and
Applications, Inc.
The easy-to-digest and approachable content makes the
rather obtuse and math-heavy jargon field of data
structures and algorithms quite approachable to all. If
you don’t like switching contexts whilst studying, this
special edition is for you, as it uses only Python to
demonstrate concepts. You can’t go wrong with this
book!

→ Paa JAKE
Software and Test Engineer
Preface
Data structures and algorithms are more than abstract
concepts. Mastering them enables you to write code that is
efficient, leading to software that runs faster and consumes
less memory. This is a big deal for today’s software
applications, which exist on increasingly mobile platforms
and handle increasingly greater amounts of data.

The problem with most resources on these subjects, though,


is that they are...well...obtuse. Most texts go heavy on the
math jargon, and if you’re not a mathematician, it can be
difficult to grasp what on earth is going on. Even books that
claim to make algorithms “easy” seem to assume that the
reader has an advanced math degree. Because of this, too
many people shy away from these concepts feeling that
they’re not “smart” enough to understand them.

The truth, though, is that everything about data structures


and algorithms boils down to common sense. Mathematical
notation itself is simply a particular language, and
everything in math can also be explained with common-
sense terminology. In this book, I use that common-sense
language (plus a lot of diagrams!) to explain these concepts
in simple and, dare I say, enjoyable ways.
Once you understand these concepts, you’ll be equipped to
write code that is efficient, fast, and elegant. You’ll be able
to weigh the pros and cons of various code alternatives and
be able to make educated decisions as to which code is best
for the given situation.

In this book, I go out of my way to make these concepts real


and practical with ideas that you can make use of today.
Sure, you’ll learn some really cool computer science along
the way. But this book is about taking that seemingly
abstract stuff and making it directly practical. You’ll be
writing better code and faster software by the time you’re
done reading this book.
Who Is This Book For?
This book is ideal for several audiences:

You’re a computer science student who wants a text


that explains data structures and algorithms in plain
English. This book can serve as a supplement to
whatever “classic” textbook you happen to be using.

You’re a beginning developer who knows basic


programming but wants to learn the fundamentals of
computer science to write better code and increase your
programming knowledge and skills.

You’re a self-taught developer who has never studied


formal computer science (or a developer who did but
forgot everything!) and wants to leverage the power of
data structures and algorithms to write more scalable
and elegant code.

Whoever you may be, I tried to write this book so that it can
be accessed and enjoyed by people of all skill levels.
The Python Edition
Pythonistas, rejoice! All the code in this book is written in
Python. The original edition of this book, A Common-Sense
Guide to Data Structures and Algorithms (the second edition
of which was published in 2020), was language-agnostic; it
was written using multiple programming languages. The
idea behind this was that we didn’t want to imply that the
book would only be helpful for one language, given that
data structures and algorithms are concepts that apply
across all of computing in general.

Over the years, I received feedback from readers who


expressed that they would love to see language-specific
editions of the book. After all, if you’re working with one
particular programming language, wouldn’t it be nice to
have a book in which all of the code is in that language?

Accordingly, I set out to create new single-language


versions of A Common-Sense Guide to Data Structures and
Algorithms. The first of these is the Python version and is
what you’re reading now! And because there’s so much to
say about data structures and algorithms, this is the first
volume in a progression of books. In this volume, I lay the
foundation for these concepts and cover the most common
data structures and algorithms. In the next volume, I’ll build
upon this knowledge to level up further with more advanced
ideas and techniques.
A Note About the Code
I strived to follow PEP 8 standards (for the most part) and
write the code in such a way so that it runs equivalently in
both Python Version 2 and Python Version 3. You can now
enjoy reading the code samples in your language of choice.

That being said, I still want to emphasize that the concepts


in this book apply to virtually all coding languages, and I
expect that some people not as familiar with Python will be
reading this book. Because of this, sometimes I have
avoided certain Python idioms where I thought that this
would utterly confuse people coming from other languages.
It’s a tricky balance to keep the code Pythonic while also
being welcoming to non-Python coders, but I hope that I’ve
maintained an equilibrium that satisfies most readers.

Virtually all the code in this book can be downloaded online


from the book’s web page.[1] This code repository contains
automated tests too! I encourage you to check that out
since the tests don’t appear in the actual book.

You’ll find some longer code snippets under the headings


that read “Code Implementation.” I certainly encourage you
to study these code samples, but you don’t necessarily have
to understand every last line to proceed to the next section
of the book. If these long pieces of code are bogging you
down, just skim (or skip) them for now.

Finally, it’s important to note that the code in this book is


not “production ready.” My greatest focus has been to
clarify the concept at hand, and while I did also try to make
the code generally complete, I have not accounted for every
edge case. There’s certainly room for you to optimize the
code further—so feel free to go crazy with that.
What’s in This Book?
As you may have guessed, this book talks quite a bit about
data structures and algorithms. More specifically, the book
is laid out as follows:

In Chapter 1, ​Why Data Structures Matter​and Chapter 2, ​


Why Algorithms Matter​, I explain what data structures and
algorithms are and explore the concept of time complexity—
which is used to determine how fast an algorithm is. In the
process, I also talk a great deal about arrays, sets, and
binary search.

In Chapter 3, ​O Yes! Big O Notation​, I unveil Big O notation


and explain it in terms that are easy to understand. We use
this notation throughout the book, so this chapter is pretty
important.

In Chapter 4, ​Speeding Up Your Code with Big O​, Chapter 5, ​


Optimizing Code With and Without Big O​, and Chapter 6, ​
Optimizing for Optimistic Scenarios ​, we delve further into
Big O notation and use it to make our day-to-day code
faster. Along the way, I cover various sorting algorithms,
including Bubble Sort, Selection Sort, and Insertion Sort.

In Chapter 7, ​Big O in Everyday Code​, you apply all that you


learned about Big O notation and analyze the efficiency of
code from the real world.

In Chapter 8, ​Blazing Fast Lookup with Hash Tables​and


Chapter 9, ​Crafting Elegant Code with Stacks and Queues​, I
discuss a few additional data structures, including hash
tables, stacks, and queues. I show how they impact the
speed and elegance of our code and how we can use them
to solve real-world problems.

Chapter 10, ​Recursively Recurse with Recursion​introduces


recursion, an anchor concept in the world of computer
science. We break it down in this chapter and see how it can
be a great tool for certain situations. Chapter 11, ​Learning
to Write in Recursive​teaches you how to write recursive
code, which can be confusing if you’re not familiar with it.

Chapter 12, ​Dynamic Programming​shows you how to


optimize recursive code and prevent it from spiraling out of
control. And Chapter 13, ​Recursive Algorithms for Speed​
shows you how to use recursion as the foundation for turbo-
fast algorithms like Quicksort and Quickselect, and then it
takes your algorithm-development skills up a few notches.

The following chapters, Chapter 14, ​Node-Based Data


Structures​, Chapter 15, ​Speeding Up All the Things with
Binary Search Trees​, Chapter 16, ​Keeping Your Priorities
Straight with Heaps​, Chapter 17, ​It Doesn’t Hurt to Trie​, and
Chapter 18, ​Connecting Everything with Graphs​, explore
node-based data structures including the linked list, the
binary tree, the heap, the trie, and the graph and show how
each is ideal for various applications.

Chapter 19, ​Dealing with Space Constraints​explores space


complexity, which is important when programming for
devices with relatively small amounts of disk space or when
dealing with big data.

The final chapter, Chapter 20, ​Techniques for Code


Optimization​, walks you through various practical
techniques for optimizing the efficiency of code and gives
you new ideas for improving the code you write every day.
How to Read This Book
You’ve got to read this book in order. In some books out
there you can read each chapter independently and skip
around a bit, but this isn’t one of them. Each chapter
assumes you’ve read the previous ones, and the book is
carefully constructed so you can ramp up your
understanding as you proceed.

That being said, there are certain chapters in the latter half
of the book that don’t depend entirely on each other. The
diagram below depicts which chapters are prerequisites for
other chapters.
For example, you could technically skip from Chapter 10 to
Chapter 13 if you wanted to. (Oh! And this diagram is based
on a data structure called a tree. You’re going to learn about
it in Chapter 15.)

Another important note: to make this book easy to


understand, I don’t always reveal everything about a
particular concept when I first introduce it. Sometimes, the
best way to break down a complex concept is to reveal a
small piece of it and only reveal the next piece once the first
piece has sunk in. If I define a particular term as such-and-
such, don’t take that to be the textbook definition until
you’ve completed the entire section on that topic.

It’s a trade-off: to make the book digestible, I’ve chosen to


oversimplify certain concepts at first and clarify them over
time rather than ensure that every sentence is completely,
academically, accurate. But don’t worry too much, because
by the end, you’ll see the entire accurate picture.
Online Resources
This book has its own web page[2] on pragprog.com where
you can find more information about the book, download the
source code for the code examples, and help improve the
book by reporting errata, typos, and content suggestions.

Additionally, I post updates about my writing at my website.


[3]
There you can find more information about my books as
well as video tutorials made by my colleagues and me in
which we use the “common-sense” approach to explaining
all sorts of technologies and concepts. We can also train
your employees! We cover all sorts of topics regarding code
efficiency and leveling up their software development skills,
including:

Writing maintainable code


Refactoring
Unit testing
And of course, writing efficient code!

My colleagues and I teach a variety of technologies, and we


always develop curriculum using the “common-sense” way
of explaining things. You can find more information at the
aforementioned website.[4]
Connecting
I enjoy connecting with my readers and invite you to find
me on LinkedIn.[5] I’d gladly accept your connection request
—just send a message that you’re a reader of this book. I
look forward to hearing from you!

Jay Wengrow
December 2023

Footnotes
[1] https://pragprog.com/titles/jwpython

[2] https://pragprog.com/titles/jwpython

[3] https://commonsensedev.com

[4] https://commonsensedev.com

[5] https://www.linkedin.com/in/jaywengrow

Copyright © 2024, The Pragmatic Bookshelf.


Acknowledgments
While the task of writing a book may seem like a solitary
one, this book simply could not have happened without the
many people who have supported me in my journey writing
it. I’d like to personally thank all of you.

To my wonderful wife, Rena—thank you for the time and


emotional support you’ve given to me. You took care of
everything while I hunkered down like a recluse and wrote.
To my adorable kids, Tuvi, Leah, Shaya, Rami, and Yechiel—
thank you for your patience as I wrote my book on
“algorizms.” And yes—it’s finally done.

To my parents, Mr. and Mrs. Howard and Debbie Wengrow—


thank you for initially sparking my interest in computer
programming and helping me pursue it. Little did you know
that getting me a computer tutor for my ninth birthday
would set the foundation for my career—and now this book.

To my wife’s parents, Mr. and Mrs. Paul and Kreindel Pinkus


—thank you for your continued support of my family and
me. Your wisdom and warmth mean so much to me.

When I first submitted my manuscript to the Pragmatic


Bookshelf, I thought it was good. However, through the
expertise, suggestions, and demands of all the wonderful
people who work there, the book has become something
much, much better than I could have written on my own.

Firstly, I’d like to thank my editor, Katharine Dvorak, for


helping get this Python edition to the finish line quickly
while also improving the book’s quality at the same time.

I’d also like to thank Tammy Coron, managing editor of the


Pragmatic Bookshelf, for overseeing this project. (And
thanks for generating all of the Python-specific images!)

Thank you to Dave Rankin, CEO of the Pragmatic Bookshelf,


for leading the best publishing company to write for as well
as for supporting and sharing my vision for creating the
language-specific editions of this book.

To Brian MacDonald, the editor of the original editions—


thank you for showing me how a book like this should be
written. This book has your imprint all over it.

To the extremely talented software developer and artist,


Colleen McGuckin—thank you for taking my chicken scratch
and transforming it into beautiful digital imagery. This book
would be nothing without the spectacular visuals you’ve
created with such skill and attention to detail.

I’ve been fortunate that so many experts have reviewed this


book. Your feedback has been extremely helpful and has
made sure that this book can be as accurate as possible. I’d
like to thank all of you for your contributions.

The reviewers of the original editions were: Alessandro


Bahgat, Ivo Balbaert, Rinaldo Bonazzo, Alberto Boschetti,
Mike Browne, Craig Castelaz, Jacob Chae, Javier Collado,
Zulfikar Dharmawan, Ashish Dixit, Dan Dybas, Emily Ekhdal,
Mohamed Fouad, Derek Graham, Neil Hainer, Peter
Hampton, Rod Hilton, Jeff Holland, Jessica Janiuk, Aaron
Kalair, Stephan Kämper, Grant Kazan, Arun S. Kumar, Sean
Lindsay, Nigel Lowry, Joy McCaffrey, Dary Merckens, Nouran
Mhmoud, Kevin Mitchell, Daivid Morgan, Brent Morris,
Jasdeep Narang, Emanuele Origgi, Stephen Orr, Kenneth
Parekh, Jason Pike, Sam Rose, Ayon Roy, Frank Ruiz, Brian
Schau, Tibor Simic, Matteo Vaccari, Mitchell Volk, Stephen
Wolff, and Peter W. A. Wood.

The reviewers of this Python edition are: Connor Baskin,


Katy Douglas, Tzvi Friedman, Joey Gallotta, Rod Hilton, Paa
JAKE, Patrick Nikolaus, Nathan Pena, Terry Peppers, Lyndon
Purcell, Cody Rutt, Brian Schau, Ahmad Shahba, and Joe
Yakich.

In addition to the official reviewers, I’d also like to thank all


the beta book readers who provided feedback as I continued
to write and edit the book. Your suggestions, comments, and
questions have been invaluable.

I’d also like to thank all the staff, students, and alumni at
Actualize for your support. This book was originally an
Actualize project, and you’ve all contributed in various ways.
I’d like to particularly thank Luke Evans for giving me the
idea to write this book.

Thank you all for making this book a reality.

Copyright © 2024, The Pragmatic Bookshelf.


Chapter 1

Why Data Structures


Matter
When people first learn to code, their focus is—and should
be—on getting their code to run properly. Their code is
measured using one simple metric: does the code actually
work?

As software engineers gain more experience, though, they


begin to learn about additional layers and nuances
regarding the quality of their code. They learn that there
can be two snippets of code that both accomplish the same
task, but that one snippet is better than the other.

There are numerous measures of code quality. One


important measure is code maintainability. Maintainability of
code involves aspects such as the readability, organization,
and modularity of one’s code.

However, another aspect of high-quality code is code


efficiency. For example, you can have two code snippets
that both achieve the same goal, but one runs faster than
the other.
Take a look at these two functions, both of which print all
the even numbers from 2 to 100:

​ ​
def​p​rint_numbers_version_one​():
​ number = 2

​ w​hile​number <= 100:
​ #​ If number is even, print it:​
​ i​f​number % 2 == 0:
​ p​rint​
(number)

​ number += 1

​ ​
def​p​rint_numbers_version_two​():
​ number = 2

​ w​hile​number <= 100:
​ p​rint​
(number)

​ #​ Increase number by 2, which, by definition,​
​ #​ is the next even number:​
​ number += 2

Which of these functions do you think runs faster?

If you said Version 2, you’re right. This is because Version 1


ends up looping 100 times, while Version 2 only loops 50
times. The first version then, takes twice as many steps as
the second version.

This book is about writing efficient code. Having the ability


to write code that runs quickly is an important aspect of
becoming a better software developer.

The first step in writing fast code is to understand what data


structures are and how different data structures can affect
the speed of our code. So let’s dive in.
Data Structures
Let’s talk about data.

Data is a broad term that refers to all types of information,


down to the most basic numbers and strings. In the simple
but classic “Hello World!” program, the string "Hello World!" is a
piece of data. In fact, even the most complex pieces of data
usually break down into a bunch of numbers and strings.

Data structures refer to how data is organized. You’re going


to learn how the same data can be organized in a variety of
ways.

Let’s look at the following code:

​ x = "Hello! "
​ y = "How are you "
​ z = "today?"

​ print(x + y + z)

This simple program deals with three pieces of data,


outputting three strings to make one coherent message. If
we were to describe how the data is organized in this
program, we’d say that we have three independent strings,
each contained within a single variable.

However, this same data can also be stored in an array:

​ array = ["Hello! ", "How are you ", "today?"]



​ print(array[0] + array[1] + array[2])

You’re going to learn in this book that the organization of


data doesn’t just matter for organization’s sake, but can
significantly impact how fast your code runs. Depending on
how you choose to organize your data, your program may
run faster or slower by orders of magnitude. And if you’re
building a program that needs to deal with lots of data, or a
web app used by thousands of people simultaneously, the
data structures you select may affect whether your software
runs at all or simply conks out because it can’t handle the
load.

When you have a solid grasp on data structures’


performance implications on the software you’re creating,
you’ll have the keys to write fast and elegant code, and your
expertise as a software engineer will be greatly enhanced.

In this chapter, we’re going to begin our analysis of two data


structures: arrays and sets. While the two data structures
may seem almost identical, you’re going to learn the tools
to analyze the performance implications of each choice.
The Array: The Foundational Data
Structure
The array is one of the most basic data structures in
computer science. (In Python, the built-in array-like data
structure is called a list, but I’ll refer to them as arrays,
keeping in line with the more general computer science
term.) I assume you’ve worked with arrays before, so you’re
aware that an array is a list of data elements. The array is
versatile and can serve as a useful tool in many situations,
but let’s take a look at one quick example.

If you’re looking at the source code for an application that


allows users to create and use shopping lists for the grocery
store, you might find code like this:

​ array = ["apples", "bananas", "cucumbers", "dates", "elderberries"]

This array happens to contain five strings, each representing


something that I might buy at the supermarket. (You’ve got
to try elderberries.)

Arrays come with their own technical jargon.

The size of an array is how many data elements the array


holds. Our grocery list array has a size of 5 since it contains
five values.

The index of an array is the number that identifies where a


piece of data lives inside the array.

In most programming languages, we begin counting the


index at 0. So for our example array, "apples" is at index 0,
and "elderberries" is at index 4, like this:

Data Structure Operations


To understand the performance of any data structure—such
as the array—we need to analyze the common ways our
code might interact with that data structure.

Many data structures are used in four basic ways, which we


refer to as operations. These operations are:

Read: Reading refers to looking something up at a


particular spot within the data structure. With an array,
this means looking up a value at a particular index. For
example, looking up which grocery item is located at
index 2 would be reading from the array.

Search: Searching refers to looking for a particular value


within a data structure. With an array, this means
looking to see if a particular value exists within the
array and, if so, at which index. For example, looking up
the index of "dates" in our grocery list would be searching
the array.

Insert: Insertion refers to adding a new value to our data


structure. With an array, this means adding a new value
to an additional slot within the array. If we were to add
"figs" to our shopping list, we’d be inserting a new value
into the array.
Delete: Deletion refers to removing a value from our
data structure. With an array, this means removing one
of the values from the array. For example, if we removed
"bananas" from our grocery list, this value would be
deleted from the array.

In this chapter, we’ll analyze how fast each of these


operations is when applied to an array.
Measuring Speed
So how do we measure the speed of an operation?

If you take away just one thing from this book, let it be this:
when we measure how “fast” an operation is, we do not
refer to how fast the operation takes in terms of pure time,
but instead in how many steps it takes.

We’ve actually seen this earlier in the context of printing the


even numbers from 2 to 100. The second version of that
function was faster because it took half as many steps as
the first version did.

Why do we measure code’s speed in terms of steps?

We do this because we can never say definitively that any


operation takes, say, five seconds. While a piece of code
may take five seconds on a particular computer, that same
piece of code may take longer on an older piece of
hardware. For that matter, that same code might run much
faster on the supercomputers of tomorrow. Measuring the
speed of an operation in terms of time is undependable,
since the time will always change depending on the
hardware it’s run on.

However, we can measure the speed of an operation in


terms of how many computational steps it takes. If
Operation A takes 5 steps, and Operation B takes 500 steps,
we can assume that Operation A will always be faster than
Operation B on all pieces of hardware. Measuring the
number of steps is, therefore, the key to analyzing the
speed of an operation.
Exploring the Variety of Random
Documents with Different Content
From whence the race of Alban fathers come
And the long glories of majestic Rome.

—Dryden.

I sing of arms, I sing of him, who from the Trojan land,


Thrust forth by Fate, to Italy and that Lavinian strand
First came: all tost about was he on earth and on the deep
By heavenly might for Juno’s wrath, that had no mind to sleep:
And plenteous war he underwent ere he his town might frame,
And set his gods in Latian earth, whence is the Latin name.
And father-folk of Alba-town, and walls of mighty Rome.

—Morris.

Arms and the man I sing, who first,


By Fate of Ilian realm amerced,
To fair Italia onward bore,
And landed on Lavinium’s shore:—
Long tossing earth and ocean o’er,
By violence of heaven, to sate
Fell Juno’s unrelenting hate;
Much labored too in battle-field,
Striving his city’s walls to build,
And give his gods a home:
Thence come the hardy Latin brood,
The ancient sires of Alba’s blood,
And lofty-rampired Rome.

—Conington.

I sing of arms, and of the man who first


Came from the coasts of Troy to Italy
And the Lavinian shores, exiled by fate,
Much was he tossed about upon the lands
And in the ocean by supernal powers,
Because of cruel Juno’s sleepless wrath.
Many things also suffered he in war,
Until he built a city, and his gods
Brought into Latium; whence the Latin race,
The Alban sires and walls of lofty Rome.

—Cranch.
I sing of war, I sing the man who erst,
From off the shore of Troy fate-hunted, came
To the Lavinian coast in Italy,
Hard pressed on land and sea, the gods malign,
Fierce Juno’s hate unslaked. Much too in war
He bore while he a city built, and set
His gods in Latium. Thence the Latin race,
Our Alban sires, the walls of haughty Rome.

—Long.

Arms and the man I sing who first, from Troy


Expelled by Fate’s decree, to Italy
And the Lavinian shores, a wanderer came.
Sore travail he endured by land and sea
From adverse gods, and unrelenting rage
Of haughty Juno: harassed, too, by war,
His destined city while he strove to build
And raise new altars for his exiled gods.
The Latian race, the Alban fathers hence
Their birth derived—hence Rome’s proud fabric sprung.

—Rickards.

(In hexameters.)
Arms and the hero I sing, who of old from the borders of Troja
Came to Italia, banished by fate to Lavinia’s destined
Sea coasts: Much was he tossed on the lands and the deep by enlisted
Might of supernals, through Juno’s remembered resentment:
Much, too, he suffered in warfare, while he was founding a city,
And into Latium bearing his gods: whence issued the Latin
Race, and the Alban fathers, and walls of imperial Roma.

—Crane.

Sing I the arms and the man, who first from the shores of the Trojan,
Driven by Fate, into Italy came, to Lavinium’s borders
Much was he vexed by the power of the gods, on the land and the ocean,
Through the implacable wrath of the vengeful and pitiless Juno;
Much, too, he suffered in war, until he could found him a city,
And into Latium carry his gods; whence the race of the Latins,
Alba’s illustrious fathers, and Rome’s imperial bulwarks.
—Howland.

Chronological Table

b.c.
98. Birth of Lucretius.
87. Birth of Catullus.
70. Virgil is born.
69. Birth of Mæcenas; Cicero is ædile.
66. Cicero is prætor.
65. Horace is born.
63. Birth of Octavius (afterward Gaius Julius Cæsar Octavianus
Augustus). Cicero’s consulship and Orations against
Catiline.
60. First Triumvirate (Cæsar, Pompey, and Crassus).
58. Cicero banished. Cæsar begins conquest of Gaul.
57. Cicero recalled from exile.
55. Virgil assumes the toga virilis. Death of Lucretius, Cæsar in
Britain.
54. Virgil studies in Milan. Death of Catullus. Cicero edits
Lucretius’ On Nature, and (perhaps) Catullus’ Odes, and
begins his essay On the State.
53. Virgil goes to Rome: Horace is also taken there. Cicero is
augur. Parthians defeat Romans at Carrhæ.
52. Cicero’s Oration for Milo.
51. Cicero proconsul in Cilicia.
49. Civil War. Cæsar marches on Rome, bestowing Roman
citizenship on Italians north of the Po. Pompey leaves
Italy.
48. Battle of Pharsalia. Assassination of Pompey.
46. Battle of Thapsus. Suicide of Cato at Utica.
45. Horace goes to Athens.
44. Cæsar assassinated: Octavius, adopted in his will, assumes
his name. Cicero’s Philippics.
43. Birth of Ovid. Second Triumvirate (Octavianus, Antony, and
Lepidus). Assassination of Cicero. Civil war with Brutus
and Cassius. Horace a tribune in Brutus’ army.
42. Battles of Philippi. Death of Brutus and Cassius.
41. Confiscations by the triumvirs. Virgil introduced to Mæcenas
and Octavianus. Horace returns to Rome.
40. Virgil restored to his estate.
39. Horace introduced to Mæcenas by Virgil and Varius.
37. Virgil publishes Eclogues. Phraates king of Parthia.
36. Antony invades Parthia.
35. Horace publishes First Book of Satires.
33. Phraates attacks Armenia and Media.
31. Battle of Actium. Overthrow of Antony. Octavianus visits the
East.
30. Horace publishes Second Book of Satires and his Epodes.
29. Octavianus returns from the East and celebrates threefold
triumph. Temple of Janus closed in sign of peace. Virgil
publishes Georgics.
27. Octavianus receives the title of Augustus.
26. Augustus in Spain corresponds with Virgil.
24. Horace (probably) publishes first Three Books of Odes.
23. Death of Marcellus. Virgil reads portions of the Æneid to
Augustus.
20. Expedition of Augustus to the East. Parthians restore
standards taken at Carrhæ.
19. Virgil journeys to Greece. Returns with Augustus. Dies at
Brundisium. Augustus directs Virgil’s friend Varius and
Tucca to edit the Æneid.
18. Horace publishes First Book of Epistles.
17. The Secular Festival. Horace writes the Secular Hymn.
13. Horace publishes Fourth Book of Odes.
8. Death of Mæcenas and Horace.
Verse Translations Recommended
Dryden; Conington (Crowell, New York); William Morris (Roberts
Brothers, Boston); Cranch; Long (Lockwood Brooks & Co., Boston);
Crane (Baker & Taylor Co., New York); Howland (D. Appleton & Co.,
New York), Rickards (Books I.-VI., Blackwood & Sons, London);
Rhoades (Longmans); Billson (Edward Arnold, London).

Books for Reference


Roman Poets of the Augustan Age, Sellar (Oxford, Clarendon
Press); Virgil, Nettleship (Appletons), and in his Lectures and Essays
(Oxford); Classical Essays, F. W. H. Myers (Macmillan); Studies in
Virgil, Glover (Edward Arnold, London); Country of Horace and Virgil,
Boissier (Putnam); Master Virgil, Tunison (Robert Clark & Co.,
Cincinnati); Vergil in the Middle Ages, Comparetti (Sonnenschein,
London); Legends of Virgil, Leland (Macmillan); Histories of Roman
Literature by Teuffel (George Bell & Sons, London), Browne (Bentley,
London), Cruttwell (Scribners, N.Y.), Simcox (Harpers, N.Y.). Æneas
as a Character Study, Miller (Latine, Vol. IV., p. 18).

Subjects for Investigation


(Miller, in Latine for January, 1886.)
(1) Virgilian Proverbs. (2) A Word Study. (3) Fatalism in Virgil. (4)
Virgil’s Pictures of Roman Customs. (5) Pen Pictures. (6) Astronomy
in Virgil. (7) Virgil’s Debt to Homer. (8) Milton’s Debt to Virgil. (9)
Virgil’s Gods and Religious Rites. (10) Omens and Oracles. (11)
Virgil’s Influence upon Literature in General. (12) Figures in Virgil.
(13) Virgilian Herbarium. (14) Detailed Account of the Wandering of
Æneas. (15) The Geography of Virgil. (16) Virgil as a Poet of Nature.
(17) Virgil’s Life as gleaned from his Works. [(18) The Manuscript
Texts of Virgil.] (19) Virgilian Translators and Commentators. (20)
Some Noted Passages—why? (21) The Platonism of the Sixth Book.
(22) Dryden’s Dictum Discussed, (23) Dante—The Later Virgil. [(24)
The Prosody of Virgil.] (25) Dido—A Psychological Study. (28) Æneas
—A Character Study. [(27) Testimonium Veterum de Vergilio.] (28)
Virgil and Theocritus. (29) Virgil’s Creations. (30) Epithets of Æneas.
(31) The Virgilian Birds. (32) Was Virgil Acquainted with the Hebrew
Scriptures? (33) Visions and Dreams—Supernatural Means of Spirit
Communication. (34) Night Scenes in Virgil. (35) Different Names for
Trojans and Greeks and their Significance. (36) The Story of the
Æneid.
VIRGIL’S ÆNEID
THE ÆNEID
BOOK I
Arms and the man I sing,[1] who at the first from Troy’s[2]
shores the exile of destiny, won his way to Italy and her
Latian[3] coast—a man much buffeted on land and on the
deep by violence from above, to sate the unforgetting wrath
of Juno[4] the cruel—much[5] scourged too in war, as he 5
struggled to build him a city, and find his gods a home in
Latium—himself the father of the Latian people, and the
chiefs of Alba’s[6] houses, and the walls of high towering
Rome.

Bring to my mind, O Muse,[7] the causes—for what 10


treason against her godhead, or what pain received, the
queen of heaven drove a man of piety so signal to turn
the wheel of so many calamities, to bear the brunt of so
many hardships! Can heavenly natures hate[8] so fiercely
and so long? 15

Of old there was a city, its people emigrants from


Tyre,[9] Carthage, over against Italy and Tiber’s mouths,
yet far removed—rich and mighty, and formed to all
roughness by war’s[10] iron trade—a spot where Juno, it
was said, loved to dwell more than in all the world beside, 20
Samos[11] holding but the second place. Here was her
armour, here her chariot—here to fix by her royal act
the empire of the nations, could Fate be brought to assent,
was even then her aim, her cherished scheme. But she
had heard that the blood of Troy was sowing the seed of a 25
race to overturn one day those Tyrian towers—from that
seed a nation, monarch of broad realms and glorious in
war, was to bring ruin on Libya[12]—such the turning of
Fate’s[13] wheel. With these fears Saturn’s[14] daughter, and
with a lively memory of that old war which at first she
had waged at Troy for her loved Argos’[15] sake—nor indeed
had the causes of that feud and the bitter pangs
they roused yet vanished from her mind—no, stored up 5
in her soul’s depths remains the judgment of Paris,[16] and
the wrong done to her slighted beauty, and the race abhorred
from the womb, and the state enjoyed by the
ravished Ganymede.[17] With this fuel added to the fire,
the Trojans, poor remnants of Danaan[18] havoc and 10
Achilles’[19] ruthless spear, she was tossing from sea to sea,
and keeping far away from Latium; and for many long
years they were wandering, with destiny still driving
them, the whole ocean round. So vast the effort it cost
to build up the Roman nation! 15

Scarce out of sight of the land of Sicily were they spreading


their sails merrily to the deep, and scattering with
their brazen prows the briny spray, when Juno, the everlasting
wound still rankling in her heart’s core, thus communed
with herself: “And am I to give up what I have 20
taken in hand, baffled, nor have power to prevent the king
of the Teucrians[20] from reaching Italy—because, forsooth,
the Fates forbid me? What! was Pallas[21] strong enough
to burn up utterly the Grecian fleet, and whelm the crews
in the sea, for the offence of a single man, the frenzy of 25
Ajax,[22] Oïleus’ son? Aye, she with her own hand launched
from the clouds Jove’s[23] winged fire, dashed the ships apart,
and turned up the sea-floor with the wind—him, gasping
out the flame which pierced his bosom, she caught in the
blast, and impaled on a rock’s[24] point—while I, who walk 30
the sky as its queen, Jove’s sister and consort both, am
battling with a single nation these many years. And are
there any found to pray to Juno’s deity after this, or lay
on her altar a suppliant’s gift?”

With such thoughts sweeping through the solitude of 35


her enkindled breast, the goddess comes to the storm-cloud’s
birthplace, the teeming womb of fierce southern
blasts, Æolia.[25] Here, in a vast cavern,[26] King Æolus[27]
is bowing to his sway struggling winds and howling tempests,
and bridling them with bond[28] and prison. They,
in their passion, are raving at the closed doors, while the
huge rock roars responsive: Æolus is sitting aloft in his
fortress, his sceptre in his hand, soothing their moods 5
and allaying their rage; were he to fail in this, why sea
and land, and the deep of heaven, would all be forced
along by their blast, and swept through the air. But
the almighty sire has buried them in caverns dark and
deep, with this fear before his eyes, and placed over them 10
giant bulk and tall mountains, and given them a king
who, by the terms of his compact, should know how to
tighten or slacken the reins at his patron’s will. To him
it was that Juno then, in these words, made her humble
request:— 15

“Æolus—for it is to thee that the sire of gods and king


of men has given it with the winds now to calm, now to
rouse the billows—there is a race which I love not now
sailing the Tyrrhene[29] sea, carrying Ilion[30] into Italy and
Ilion’s vanquished gods; do thou lash the winds to fury, 20
sink and whelm their ships, or scatter them apart, and
strew the ocean with their corpses. Twice seven nymphs
are of my train, all of surpassing beauty; of these her whose
form is fairest, Deiopea, I will unite to thee in lasting wedlock,
and consecrate her thy own, that all her days, for a 25
service so great, she may pass with thee, and make thee
father of a goodly progeny.”

Æolus returns: “Thine, great Queen, is the task to


search out on what thou mayest fix thy heart; for me to do
thy bidding[31] is but right. Thou makest this poor realm 30
mine, mine the sceptre and Jove’s smile; thou givest me a
couch at the banquets of the gods, and makest me lord
of the storm-cloud and of the tempest.”

So soon as this was said, he turned his spear, and pushed


the hollow mountain on its side; and the winds, as though 35
in column formed, rush forth[32] where they see any outlet,
and sweep over the earth in hurricane. Heavily they
fall[33] on the sea, and from its very bottom crash down the
whole expanse—one and all, east and south, and south-west,
with his storms thronging at his back, and roll huge
billows shoreward. Hark to the shrieks of the crew, and
the creaking of the cables! In an instant the clouds
snatch sky and daylight[34] from the Teucrians’ eyes—night 5
lies on the deep, black and heavy—pole thunders to
pole; heaven flashes thick with fires, and all nature
brandishes instant death in the seaman’s face. At once
Æneas’[35] limbs are unstrung and chilled[36]—he groans
aloud, and, stretching his clasped hands to the stars, 10
fetches from his breast words like these:—“O happy,
thrice[37] and again, whose lot it was, in their fathers’ sight,
under Troy’s high walls to meet death! O thou, the bravest
of the Danaan race, Tydeus’ son,[38] why was it not mine
to lay me low on Ilion’s plains, and yield this fated life to 15
thy right hand? Aye, there it is that Hector,[39] stern as
in life, lies stretched by the spear of Æacides[40]—there
lies Sarpedon’s[41] giant bulk—there it is that Simois[42]
seizes and sweeps down her channel those many shields
and helms, and bodies of the brave!” 20
Such words as he flung wildly forth, a blast roaring from
the north strikes his sail full in front and lifts the billows
to the stars.[43] Shattered are the oars; then the prow
turns and presents the ship’s side to the waves; down
crashes in a heap a craggy mountain of water. Look! 25
these are hanging on the surge’s crest[44]—to those the
yawning deep is giving a glimpse of land down among
the billows; surf and sand are raving together. Three
ships the south catches, and flings upon hidden rocks—rocks 30
which, as they stand with the waves all about them,
the Italians call Altars, an enormous ridge rising above
the sea. Three the east drives from the main on to shallows
and Syrtes,[45] a piteous sight, and dashes them on
shoals, and embanks them in mounds of sand. One in
which the Lycians were sailing, and true Orontes, a 35
mighty sea strikes from high on the stem before Æneas’
very eyes; down goes the helmsman, washed from his
post, and topples on his head, while she is thrice whirled
round by the billow in the spot where she lay, and swallowed
at once by the greedy gulf. You might see them
here and there swimming in that vast abyss—heroes’
arms, and planks, and Troy’s treasures glimmering through
the water. Already Ilioneus’ stout ship, already brave 5
Achates’, and that in which Abas sailed, and that which
carried old Aletes, are worsted by the storm; their side-jointings[46]
loosened, one and all give entrance to the
watery foe, and part failingly asunder.

Meantime the roaring riot of the ocean and the storm let 10
loose reached the sense of Neptune,[47] and the still waters
disgorged from their deep beds, troubling him grievously;
and casting a broad glance over the main he raised at
once his tranquil brow from the water’s surface. There
he sees Æneas’ fleet tossed hither and thither over the 15
whole expanse—the Trojans whelmed under the billows,
and the crashing ruin of the sky—nor failed the brother
to read Juno’s craft and hatred there. East and West
he calls before him, and bespeaks them thus:—“Are ye
then so wholly o’ermastered by the pride of your birth? 20
Have ye come to this, ye Winds, that, without sanction
from me, ye dare to confound[48] sea and land, and upheave
these mighty mountains? ye! whom I—but it were best
to calm the billows ye have troubled. Henceforth ye
shall pay me for your crimes in far other coin. Make 25
good speed with your flight, and give your king this message.
Not to him did the lot assign the empire of the sea
and the terrible trident, but to me. His sway is over those
enormous rocks, where you, Eurus,[49] dwell, and such as
you; in that court let Æolus lord it, and rule in the prison-house 30
of the winds when its doors are barred.”

He speaks, and ere his words are done soothes the swelling
waters, and routs[50] the mustered clouds, and brings
back the sun in triumph. Cymothoë and Triton[51] combine
their efforts to push off the vessels from the sharp-pointed 35
rock. The god himself upheaves them with his
own trident,[52] and levels the great quicksands, and allays
the sea, and on chariot-wheels of lightest motion glides
along the water’s top. Even as when in a great crowd tumult
is oft stirred up, and the base herd waxes wild and frantic,
and brands and stones are flying already, rage suiting
the weapon[53] to the hand—at that moment, should their
eyes fall on some man of weight, for duty done and public 5
worth, tongues are hushed and ears fixed in attention,
while his words sway the spirit and soothe the breast—so
fell all the thunders of the ocean, so soon as the great
father, with the waves before him in prospect, and the
clear sky all about him, guides his steeds at will, and as he 10
flies flings out the reins freely to his obedient car.
Spent with toil, the family of Æneas labour to gain the
shore that may be nearest, and are carried to the coasts
of Libya. There is a spot retiring deep into the land, where
an island forms a haven[54] by the barrier of its sides, which 15
break every billow from the main and send it shattered
into the deep indented hollows. On either side of the bay are
huge rocks, and two great crags rising in menace to the
sky; under their summits far and wide the water is hushed
in shelter, while a theatric background of waving woods, 20
a black forest of stiffening shade, overhangs it from the
height. Under the brow that fronts the deep is a cave
with pendent crags; within there are fresh springs and
seats in the living rock—the home of the nymphs; no
need of cable[55] here to confine the weary bark or anchor’s 25
crooked fang to grapple her to the shore. Here with seven
ships mustered from his whole fleet Æneas enters; and
with intense yearning for dry land the Trojans disembark
and take possession of the wished-for shore, and lay their
brine-drenched limbs upon the beach. And first Achates 30
from a flint struck out a spark, and received the fire as it
dropped in a cradle of leaves, and placed dry food all about
it, and spread the strong blaze among the tinder. Then
their corn, soaked and spoiled as it was, and the corn-goddess’
armoury they bring out, sick of fortune; and make 35
ready to parch the rescued grain at the fire, and crush it
with the millstone.

Æneas meanwhile clambers up a rock, and tries to get a


full view far and wide over the sea, if haply he may see
aught of Antheus, driven by the gale, and the Phrygian
biremes,[56] or Capys, or high on the stern the arms of Caicus.
Sail there is none in sight; three stags he sees at distance
straying on the shore; these the whole herd follows in the 5
rear, and grazes along the hollows in long array. At once
he took his stand, and caught up a bow and fleet arrows,
which true Achates chanced to be carrying, and lays low first
the leaders themselves, as they bear their heads aloft with
tree-like antlers, then the meaner sort, and scatters with 10
his pursuing shafts the whole rout among the leafy woods;
nor stays his hand till he stretches on earth victoriously
seven huge bodies, and makes the sum of them even with
his ships. Then he returns to the haven and gives all his
comrades their shares. The wine next, which that good 15
Acestes had stowed in casks on the Trinacrian shore, and
given them at parting with his own princely hand, he
portions out, and speaks words of comfort to their sorrowing
hearts:—

“Comrades! for comrades we are, no strangers to hardships 20


already; hearts that have felt deeper wounds! for
these too heaven will find a balm. Why, men, you have
even looked on Scylla[57] in her madness, and heard those
yells that thrill the rocks; you have even made trial of
the crags of the Cyclops.[58] Come, call your spirits back, 25
and banish these doleful fears—who knows but some
day this too will be remembered[59] with pleasure? Through
manifold chances, through these many perils of fortune,
we are making our way to Latium, where the Fates hold
out to us a quiet settlement; there Troy’s empire has 30
leave to rise again from its ashes. Bear up, and reserve
yourselves for brighter days.”

Such were the words his tongue uttered; heart-sick[60]


with overwhelming care, he wears the semblance of hope
in his face, but has grief deep buried in his heart. They 35
gird themselves to deal with the game, their forthcoming
meal; strip the hide from the ribs, and lay bare the flesh—some
cut it into pieces, and impale it yet quivering on
spits, others set up the caldrons on the beach, and supply
them with flame. Then with food they recall their
strength, and, stretched along the turf, feast on old wine
and fat venison to their hearts’ content. Their hunger
sated by the meal, and the boards removed, they vent in 5
long talk their anxious yearning for their missing comrades—
balanced
between hope and fear, whether to
think of them as alive, or as suffering the last change, and
deaf already to the voice that calls on them. But good
Æneas’ grief exceeds the rest; one moment he groans for 10
bold Orontes’ fortune, another for Amycus’, and in the
depth of his spirit laments for the cruel fate of Lycus;
for the gallant Gyas and the gallant Cloanthus.

And now at last their mourning had an end, when


Jupiter from the height of ether,[61] looking down on the sea 15
with its fluttering sails, on the flat surface of earth, the
shores, and the broad tribes of men, paused thus upon
heaven’s very summit, and fixed his downward gaze on
Libya’s realms. To him, revolving in his breast such
thoughts as these, sad beyond her wont, with tears suffusing 20
her starry eyes, speaks Venus: “O thou, who by thy
everlasting laws swayest the two commonwealths of men
and gods, and awest them by thy lightning! What can
my poor Æneas have done to merit thy wrath? What
can the Trojans? yet they, after the many deaths they 25
have suffered already, still find the whole world barred[62]
against them for Italy’s sake. From them assuredly it
was that the Romans, as years rolled on—from them were
to spring those warrior chiefs, aye from Teucer’s blood revived,
who should rule sea and land with absolute sway—such 30
was thy promise: how has thy purpose, O my father,
wrought a change in thee? This, I know, was my constant
solace when Troy’s star set in grievous ruin, as I sat balancing
destiny against destiny. And now here is the same
Fortune, pursuing the brave men she has so oft discomfited 35
already. Mighty king, what end of sufferings hast thou
to give them? Antenor,[63] indeed, found means to escape
through the midst of the Achæans, to thread in safety
the windings of the Illyrian coast, and the realms of the
Liburnians, up at the gulf’s head, and to pass the springs
of Timavus, whence through nine mouths,’mid the rocks’
responsive roar, the sea comes bursting up, and deluges
the fields with its thundering billows. Yet in that spot 5
he built the city of Patavium for his Trojans to dwell in,
and gave them a place and a name among the nations, and
set up a rest for the arms[64] of Troy: now he reposes, lapped
in the calm of peace. Meantime we, of thine own blood,
to whom thy nod secures the pinnacle of heaven, our ships, 10
most monstrous, lost, as thou seest, all to sate the malice
of one cruel heart, are given up to ruin, and severed far
from the Italian shores. Is this the reward of piety[65]?
Is this to restore a king to his throne?”

Smiling on her, the planter of gods and men, with that 15


face which calms the fitful moods of the sky, touched with
a kiss his daughter’s lips, then addressed her thus: “Give
thy fears a respite, lady of Cythera[66]: thy people’s destiny
abides still unchanged for thee; thine eyes shall see the
city of thy heart, the promised walls of Lavinium[67]; 20
thine arms shall bear aloft to the stars of heaven thy hero
Æneas; nor has my purpose wrought a change in me.
Thy hero—for I will speak out, in pity for the care that
rankles yet, and awaken the secrets of Fate’s book from
the distant pages where they slumber—thy hero shall 25
wage a mighty war in Italy, crush its haughty tribes, and
set up for his warriors a polity and a city, till the third
summer shall have seen him king over Latium, and three
winters in camp shall have passed over the Rutulians’[68]
defeat. But the boy Ascanius,[69] who has now the new 30
name of Iulus—Ilus he was, while the royalty of Ilion’s
state stood firm—shall let thirty of the sun’s great courses
fulfil their monthly rounds while he is sovereign, then
transfer the empire from Lavinium’s seat, and build
Alba the Long, with power and might. Here for full three 35
hundred years the crown shall be worn by Hector’s[70] line,
till a royal priestess, teeming by the war-god, Ilia, shall
be the mother of twin sons. Then shall there be one,
proud to wear the tawny hide of the wolf that nursed him,
Romulus, who will take up the sceptre, and build a new
city, the city of Mars, and give the people his own name
of Roman. To them I assign no limit, no date of empire:
my grant to them is dominion without end. Nay, Juno, 5
thy savage foe, who now, in her blind terror, lets neither
sea, land, nor heaven rest, shall amend her counsels, and
vie with me in watching over the Romans, lords of earth,
the great nation of the gown. So it is willed. The time
shall come, as Rome’s years roll on, when the house of 10
Assaracus[71] shall bend to its yoke Phthia[72] and renowned
Mycenæ,[73] and queen it over vanquished Argos.[74] Then shall
be born the child of an illustrious line, one of thine own
Trojans, Cæsar, born to extend his empire to the ocean, his
glory to the stars,[75]—Julius, in name as in blood the heir of 15
great Iulus. Him thou shalt one day welcome in safety to
the sky, a warrior laden with Eastern spoils; to him, as to
Æneas, men shall pray and make their vows. In his days
war[76] shall cease, and savage times grow mild. Faith with
her hoary head, and Vesta,[77] Quirinus,[78] and Remus his 20
brother, shall give law to the world: grim, iron-bound,
closely welded, the gates of war shall be closed; the fiend
of Discord a prisoner within, seated on a pile of arms deadly
as himself, his hands bound behind his back with a hundred
brazen chains, shall roar ghastly from his throat of blood.” 25
So saying, he sends down from on high the son of Maia,[79]
that Carthage the new, her lands and her towers, may
open themselves to welcome in the Teucrians, lest Dido,[80]
in her ignorance of Fate, should drive them from her
borders. Down flies Mercury through the vast abyss of 30
air, with his wings for oars, and has speedily alighted on
the shore of Libya. See! he is doing his bidding already:
the Punic[81] nation is resigning the fierceness of its nature
at the god’s pleasure; above all the rest, the queen is
admitting into her bosom thoughts of peace towards the 35
Teucrians, and a heart of kindness.

But Æneas the good, revolving many things the whole


night through, soon as the gracious dawn is vouchsafed,
resolves to go out and explore this new region; to inquire
what shores be these on which the wind has driven him,
who their dwellers, for he sees it is a wilderness, men or
beasts; and bring his comrades back the news. His
fleet he hides in the wooded cove under a hollow rock, 5
with a wall of trees and stiffening shade on each side.
He moves on with Achates, his single companion, wielding
in his hands two spear shafts, with heads of broad iron.
He had reached the middle of the wood, when his way
was crossed by his mother, wearing a maiden’s mien and 10
dress, and a maiden’s armour, Spartan, or even as Harpalyce
of Thrace, tires steed after steed, and heads the swift
waters of her own Hebrus as she flies along. For she had
a shapely bow duly slung from her shoulders in true huntress
fashion, and her hair streaming in the wind, her knee 15
bare, and her flowing scarf gathered round her in a knot.
Soon as she sees them, “Ho![82] youths,” cries she, “if you
have chanced to see one of my sisters wandering in these
parts, tell me where to find her—wandering with a quiver,
and a spotted lynx hide fastened about her; or, it may 20
be, pressing on the heels of the foaming boar with her
hounds in full cry.”

Thus Venus spoke, and Venus’ son replied:—“No sight


or hearing have we had of any sister of thine, O thou—what
name shall I give thee? maiden; for thy face is not 25
of earth, nor the tone of thy voice human: some goddess[83]
surely thou art. Phœbus’[84] sister belike, or one of the
blood of the nymphs? be gracious, whoe’er thou art, and
relieve our hardship, and tell us under what sky now,
on what realms of earth we are thrown. Utter strangers 30
to the men and the place, we are wandering, as thou seest,
by the driving of the wind and of the mighty waters.
Do this, and many a victim shall fall to thee at the altar
by this hand of mine.”

Then Venus:—“Nay, I can lay claim to no such honours. 35


Tyrian maidens, like me, are wont to carry the
quiver, and tie the purple buskin high up the calf. This
that you now see is the Punic realm, the nation Tyrian
and the town Agenor’s[85]; but on the frontiers are the
Libyans, a race ill to handle in war. The queen is Dido,
who left her home in Tyre to escape from her brother.
Lengthy is her tale of wrong, lengthy the windings of its
course; but I will pass rapidly from point to point. Her 5
husband was Sychæus, wealthiest of Phœnician landowners,
and loved by his poor wife with fervid passion;
on him her father had bestowed her in her maiden bloom,
linking them together by the omens of a first bridal. But
the crown of Tyre was on the head of her brother, Pygmalion, 10
in crime monstrous beyond the rest of men.
They were two, and fury came between them. Impious
that he was, at the very altar of the palace, the love of
gold blinding his eyes, he surprises Sychæus with his
stealthy steel, and lays him low, without a thought for 15
his sister’s passion; he kept the deed long concealed,
and with many a base coinage sustained the mockery
of false hope[86] in her pining love-lorn heart. But lo! in
her sleep there came to her no less than the semblance of
her unburied spouse, lifting up a face of strange unearthly 20
pallor; the ruthless altar and his breast gored with the
steel, he laid bare the one and the other, and unveiled
from first to last the dark domestic crime. Then he urges
her to speed her flight, and quit her home for ever, and in
aid of her journey unseals a hoard of treasure long hid in 25
the earth, a mass of silver and gold which none else knew.
Dido’s soul was stirred; she began to make ready her
flight, and friends to share it. There they meet, all whose
hate of the tyrant was fell or whose fear was bitter; ships,
that chanced to lie ready in the harbour, they seize, and 30
freight with gold. Away it floats over the deep, the
greedy Pygmalion’s wealth; and who heads the enterprise?
a woman[87]! So they came to the spot where you
now see yonder those lofty walls, and the rising citadel
of Carthage the new; there they bought ground, which 35
got from the transaction the name of Byrsa,[88] as much as
they could compass round with a bull’s hide. But who
are you after all? What coast are you come from, or
whither are you holding on your journey?” That question
he answers thus, with a heavy sigh, and a voice
fetched from the bottom of his heart:—

“Fair goddess! should I begin from the first and proceed


in order, and hadst thou leisure to listen to the chronicle 5
of our sufferings, eve would first close the Olympian gates
and lay the day to sleep. For us, bound from ancient
Troy, if the name of Troy has ever chanced to pass through
a Tyrian ear, wanderers over divers seas already, we have
been driven by a storm’s wild will upon your Libyan 10
coasts. I am Æneas, styled the good, who am bearing
with me in my fleet the gods of Troy rescued from the
foe; a name blazed by rumour above the stars. I am in
quest of Italy, looking there for an ancestral home, and a
pedigree drawn from high Jove himself. With twice ten 15
ships I climbed the Phrygian main, with a goddess mother
guiding me on my way, and a chart of oracles to follow.
Scarce seven remain to me now, shattered by wind and
wave. Here am I, a stranger, nay, a beggar, wandering
over your Libyan deserts, driven from Europe and Asia 20
alike.” Venus could bear the complaint no longer, so
she thus struck into the middle of his sorrows:—

“Whoever you are, it is not, I trow, under the frown of


heavenly powers that you draw the breath of life,[89] thus to
have arrived at our Tyrian town. Only go on, and make 25
your way straight hence to the queen’s palace. For I
give you news that your comrades are returned and your
fleet brought back, wafted into shelter by shifting gales,
unless my learning of augury was vain, and the parents
who taught me cheats. Look at these twelve swans 30
exultant in victorious column, which the bird of Jove,[90]
swooping from the height of ether, was just now driving
in confusion over the wide unsheltered sky; see now how
their line stretches, some alighting on the ground, others
just looking down on those alighted. As they, thus rallied, 35
ply their whirring wings[91] in sport, spreading their train
round the sky, and uttering songs of triumph, even so
your vessels and your gallant crews are either safe in the
port, or entering the haven with sails full spread. Only
go on, and where the way leads you direct your steps.”

She said, and as she turned away, flashed on their sight


her neck’s roseate hue; her ambrosial locks breathed from
her head a heavenly fragrance; her robe streamed down 5
to her very feet; and in her walk[92] was revealed the true
goddess. Soon as he knew his mother, he pursued her
flying steps with words like these:—“Why wilt thou be
cruel like the rest, mocking thy son these many times
with feigned semblances? Why is it not mine to grasp 10
thy hand in my hand, and hear and return the true language
of the heart?” Such are his upbraidings, while he
yet bends his way to the town. But Venus fenced them
round with a dim cloud as they moved, and wrapped them
as a goddess only can in a spreading mantle of mist, that 15
none might be able to see them, none to touch them, or
put hindrances in their path, or ask the reason of their coming.
She takes her way aloft to Paphos,[93] glad to revisit
the abode she loves, where she has a temple and a hundred
altars, smoking with Sabæan[94] incense, and fragrant with 20
garlands ever new.

They, meanwhile, have pushed on their way, where the


path guides them, and already they are climbing the hill
which hangs heavily over the city, and looks from above
on the towers that rise to meet it. Æneas marvels at the 25
mass of building, once a mere village of huts; marvels at
the gates, and the civic din, and the paved ways. The
Tyrians are alive and on fire—intent, some on carrying
the walls aloft and upheaving the citadel, and rolling
stones from underneath by force of hand; some on making 30
choice of a site for a dwelling, and enclosing it with a
trench. They are ordaining the law and its guardians, and
the senate’s sacred majesty. Here are some digging out
havens; there are others laying deep the foundation of a
theatre, and hewing from the rocks enormous columns, 35
the lofty ornaments of a stage that is to be. Such are the
toils that keep the commonwealth of bees[95] at work
in the sun among the flowery meads when summer is
new, what time they lead out the nation’s hope, the young
now grown, or mass together honey, clear and flowing, and
strain the cells to bursting with its nectarous sweets, or
relieve those who are coming in of their burdens, or collect
a troop and expel from their stalls the drones, that lazy, 5
thriftless herd. The work is all afire, and a scent of thyme
breathes from the fragrant honey. “O happy they, whose
city is rising already!” cries Æneas, as he looks upward
to roof and dome. In he goes, close fenced by his cloud,
miraculous to tell, threads his way through the midst, 10
and mingles with the citizens, unperceived of all.

A grove there was in the heart of the city, most plenteous


of shade—the spot where first, fresh from the buffeting of
wave and wind, the Punic race dug up the token which
queenly Juno had bidden them expect, the head of a fiery 15
steed—for even thus, said she, the nation should be renowned
in war and rich in sustenance for a life of centuries.
Here Dido, Sidon’s[96] daughter, was building a vast temple
to Juno, rich in offerings and in the goddess’s especial
presence; of brass was the threshold with its rising steps, 20
clamped with brass the door-posts, the hinge creaked on
a door of brass. In this grove it was that first a new object
appeared, as before, to soothe away fear: here it was that
Æneas first dared to hope that all was safe, and to place a
better trust in his shattered fortunes. For while his eye 25
ranges over each part under the temple’s massy roof, as
he waits there for the queen—while he is marvelling at
the city’s prosperous star, the various artist-hands vying
with each other, their tasks and the toil they cost, he
beholds, scene after scene, the battles of Ilion, and the 30
war that Fame had already blazed the whole world over—Atreus’[o]
sons, and Priam, and the enemy of both,
Achilles. He stopped short, and breaking into tears,
“What place is there left?” he cries, “Achates, what
clime on earth that is not full of our sad story? See there 35
Priam. Here, too, worth finds its due reward; here, too,
there are tears[97] for human fortune, and hearts that are
touched by mortality. Be free from fear: this renown
of ours will bring you some measure of safety.” So speaking,
he feeds his soul on the empty portraiture, with many
a sigh, and lets copious rivers run down his cheeks. For
he still saw how, as they battled round Pergamus,[98] here
the Greeks were flying, the Trojan youth in hot pursuit; 5
here the Phrygians, at their heels in his car Achilles, with
that dreadful crest. Not far from this he recognizes with
tears the snowy canvas of Rhesus’ tent, which, all surprised
in its first sleep, Tydeus’ son was devastating with wide
carnage, himself bathed in blood—see! he drives off 10
the fiery steeds to his own camp, ere they have had time
to taste the pastures of Troy or drink of Xanthus.[99] There
in another part is Troilus[100] in flight, his arms fallen from
him—unhappy boy, confronted with Achilles in unequal
combat—hurried away by his horses, and hanging half 15
out of the empty car, with his head thrown back, but the
reins still in his hand; his neck and his hair are being
trailed along the ground, and his inverted spear is drawing
lines in the dust. Meanwhile to the temple of Pallas,[101]
not their friend, were moving the Trojan dames with locks 20
dishevelled, carrying the sacred robe, in suppliant guise
of mourning, their breasts bruised with their hands—the
goddess was keeping her eyes riveted on the ground,
with her face turned away. Thrice had Achilles dragged
Hector round the walls of Ilion, and was now selling for 25
gold his body, thus robbed of breath. Then, indeed,
heavy was the groan that he gave from the bottom of
his heart, when he saw the spoils, the car, the very body
of his friend, and Priam, stretching out those helpless
hands. Himself, too, he recognizes in the forefront of 30
the Achæan ranks, and the squadrons of the East, and the
arms of the swarthy Memnon.[102] There, leading the columns
of her Amazons, with their moony shields, is Penthesilea[103]
in her martial frenzy, blazing out, the centre of thousands,
as she loops up her protruded breast with a girdle of gold, 35
the warrior queen, and nerves herself to the shock of combat,
a maiden against men.

While these things are meeting the wondering eyes of


Æneas the Dardan—while he is standing bewildered,
and continues riveted in one set gaze—the queen has
moved towards the temple, Dido, of loveliest presence,
with a vast train of youths thronging round her. Like
as on Eurotas’ banks, or along the ridges of Cynthus, 5
Diana[104] is footing the dance, while, attending her, a thousand
mountain nymphs are massing themselves on either
side; she, her quiver on her shoulder, as she steps, towers
over the whole goddess sisterhood, while Latona’s[105] bosom
thrills silently with delight; such was Dido—such she 10
bore herself triumphant through the midst, to speed the
work which had empire for its prospect. Then, at the doors
of the goddess, under the midmost vaulting of the temple,
with a fence of arms round her, supported high on a throne,
she took her seat. There she was giving laws and judgments 15
to her citizens, and equalizing the burden of their
tasks by fair partition, or draughting it by lot, when suddenly
Æneas sees coming among the great crowd Antheus
and Sergestus, and brave Cloanthus, and other of the
Teucrians, whom the black storm had scattered over the 20
deep, and carried far away to other coasts. Astounded
was he, overwhelmed, too, was Achates, all for joy and
fear: eagerly were they burning to join hands with theirs,
but the unexplained mystery confounds their minds.
They carry on the concealment, and look out from the 25
hollow cloud that wraps them, to learn what fortune their
mates have had, on what shore they are leaving their fleet,
what is their errand here—for they were on their way,
a deputation from all the crews, suing for grace, and were
making for the temple with loud cries. 30

After they had gained an entrance, and had obtained


leave to speak in the presence, Ilioneus, the eldest, thus
began, calm of soul:—

“Gracious queen, to whom Jupiter has given to found a


new city, and to restrain by force of law the pride of savage 35
nations, we, hapless Trojans, driven by the winds over
every sea, make our prayer to you—keep off from our
ships the horrors of fire, have pity on a pious race, and
vouchsafe a nearer view to our affairs. We are not come
to carry the havoc of the sword into the homes of Libya—to
snatch booty and hurry it to the shore; such violence
is not in our nature; such insolence were not for
the vanquished. There is a place—the Greeks call it 5
Hesperia—a land old in story, strong in arms and in
the fruitfulness of its soil; the Œnotrians were its settlers;
now report says that later generations have called the
nation Italian, from the name of their leader. Thither
were we voyaging, when, rising with a sudden swell, Orion,[106] 10
lord of the storm, carried us into hidden shoals, and far
away by the stress of reckless gales over the water, the
surge mastering us, and over pathless rocks scattered us
here and there: a small remnant, we drifted hither on to
your shores. What race of men have we here? What 15
country is so barbarous as to sanction a native usage like
this? Even the hospitality of the sand is forbidden us—they
draw the sword, and will not let us set foot on the
land’s edge. If you defy the race of men, and the weapons
that mortals wield, yet look to have to do with gods, who 20
watch over the right and the wrong. Æneas was our king,
than whom never man breathed more just, more eminent
in piety, or in war and martial prowess. If the Fates are
keeping our hero alive—if he is feeding on this upper
air, and not yet lying down in death’s cruel shade—all 25
our fears are over, nor need you be sorry to have made
the first advance in the contest of kindly courtesy. The
realm of Sicily, too, has cities for us, and store of arms,
and a hero-king of Trojan blood, Acestes.[o] Give us leave
but to lay up on shore our storm-beaten fleet, to fashion 30
timber in your forests, and strip boughs for our oars, that,
if we are allowed to sail for Italy, our comrades and king
restored to us, we may make our joyful way to Italy and
to Latium; or, if our safety is swallowed up, and thou,
best father of the Teucrians, art the prey of the Libyan 35
deep, and a nation’s hope lives no longer in Iulus, then, at
least, we may make for Sicania’s straits, and the houses
standing to welcome us, whence we came hither, and may
find a king in Acestes.” Such was the speech of Ilioneus;
an accordant clamour burst at once from all the sons of
Dardanus.

Then briefly Dido, with downcast look, makes reply:—“Teucrians!


unburden your hearts of fear, lay your anxieties 5
aside. It is the stress of danger and the infancy of
my kingdom that make me put this policy in motion and
protect my frontiers with a guard all about. The men
of Æneas and the city of Troy—who can be ignorant of
them?—the deeds and the doers, and all the blaze of that 10
mighty war? Not so blunt are the wits we Punic folk
carry with us, not so wholly does the sun turn his back
on our Tyrian town when he harnesses his steeds.
Whether you make your choice of Hesperia the great, and
the old realm of Saturn, or of the borders of Eryx and their 15
king Acestes, I will send you on your way with an escort
to protect you, and will supply you with stores. Or would
you like to settle along with me in my kingdom here?
Look at the city I am building, it is yours, lay up your
ships, Trojan and Tyrian shall be dealt with by me without 20
distinction. Would to heaven your king were here too,
driven by the gale that drove you hither—Æneas himself!
For myself, I will send trusty messengers along the coast,
with orders to traverse the furthest parts of Libya, in case
he should be shipwrecked and wandering anywhere in 25
forest or town.”

Excited by her words, brave Achates and father Æneas,


too, were burning long ere this to break out of their cloud.
Achates first accosts Æneas:—“Goddess-born, what purpose
now is foremost in your mind? All you see is safe, 30
our fleet and our mates are restored to us. One is missing,
whom our own eyes saw in the midst of the surge swallowed
up, all the rest is even as your mother told us.”

Scarce had he spoken when the cloud that enveloped


them suddenly parts asunder and clears into the open sky. 35
Out stood Æneas, and shone[107] again in the bright sunshine,
his face and his bust the image of a god, for his great
mother had shed graceful tresses over her son’s brow,
and the glowing flush of youth, and had breathed the
breath of beauty and gladness into his eyes, loveliness such
as the artist’s touch imparts to ivory, or when silver or
Parian marble is enchased[108] with yellow gold. Then he
addresses the queen, and speaks suddenly to the astonishment 5
of all:—“Here am I whom you are seeking, before
you,—Æneas, the Trojan, snatched from the jaws of the
Libyan wave. O heart that alone of all has found pity for
Troy’s cruel agonies—that makes us, poor remnants of
Danaan fury, utterly spent by all the chances of land and 10
sea, destitute of all, partners of its city, of its very palace!
To pay such a debt of gratitude, Dido, is more than we can
do—more than can be done by all the survivors of the
Dardan nation, now scattered the wide world over. May
the gods—if there are powers that regard the pious, if 15
justice and conscious rectitude count for aught anywhere
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!

ebookfinal.com

You might also like