0% нашли этот документ полезным (0 голосов)
40 просмотров21 страница

2014 Bookmatter PythonAlgorithms

Загружено:

bkmurthy81
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
0% нашли этот документ полезным (0 голосов)
40 просмотров21 страница

2014 Bookmatter PythonAlgorithms

Загружено:

bkmurthy81
Авторское право
© © All Rights Reserved
Мы серьезно относимся к защите прав на контент. Если вы подозреваете, что это ваш контент, заявите об этом здесь.
Доступные форматы
Скачать в формате PDF, TXT или читать онлайн в Scribd
Вы находитесь на странице: 1/ 21

Python Algorithms

Mastering Basic Algorithms


in the Python Language

Second Edition

Magnus Lie Hetland


Python Algorithms: Mastering Basic Algorithms in the Python Language
Copyright © 2014 by Magnus Lie Hetland
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material
is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting,
reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval,
electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material
supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the
purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the
Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from
Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are
liable to prosecution under the respective Copyright Law.
ISBN-13 (pbk): 978-1-4842-0056-8
ISBN-13 (electronic): 978-1-4842-0055-1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified
as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither
the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may
be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Publisher: Heinz Weinheimer
Lead Editor: Steve Anglin
Technical Reviewer: Stefan Turalski
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan,
James T. DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham,
Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft,
Gwenan Spearing, Matt Wade, Steve Weiss
Development Editor: Kenyon Brown
Coordinating Editor: Anamika Panchoo
Copy Editor: Kim Wimpsett
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover Designer: Anna Ishchenko
Photo Credit: Kai T. Dragland
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor,
New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com,
or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook
Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this text is available to readers at
www.apress.com. For detailed information about how to locate your book’s source code,
go to www.apress.com/source-code/.
For JV, the silliest girl I know.
Contents at a Glance

About the Author���������������������������������������������������������������������������������������������������������������� xv


About the Technical Reviewer������������������������������������������������������������������������������������������ xvii
Acknowledgments������������������������������������������������������������������������������������������������������������� xix
Preface������������������������������������������������������������������������������������������������������������������������������ xxi

■■Chapter 1: Introduction�����������������������������������������������������������������������������������������������������1

■■Chapter 2: The Basics�������������������������������������������������������������������������������������������������������9

■■Chapter 3: Counting 101�������������������������������������������������������������������������������������������������43

■■Chapter 4: Induction and Recursion ... and Reduction����������������������������������������������������67

■■Chapter 5: Traversal: The Skeleton Key of Algorithmics�������������������������������������������������93

■■Chapter 6: Divide, Combine, and Conquer���������������������������������������������������������������������115

■■Chapter 7: Greed Is Good? Prove It! �����������������������������������������������������������������������������139

■■Chapter 8: Tangled Dependencies and Memoization����������������������������������������������������163

■■Chapter 9: From A to B with Edsger and Friends����������������������������������������������������������187

■■Chapter 10: Matchings, Cuts, and Flows ����������������������������������������������������������������������209

■■Chapter 11: Hard Problems and (Limited) Sloppiness��������������������������������������������������227

v
■ Contents at a Glance

■■Appendix A: Pedal to the Metal: Accelerating Python���������������������������������������������������255

■■Appendix B: List of Problems and Algorithms���������������������������������������������������������������259

■■Appendix C: Graph Terminology������������������������������������������������������������������������������������267

■■Appendix D: Hints for Exercises������������������������������������������������������������������������������������273

Index���������������������������������������������������������������������������������������������������������������������������������289

vi
Contents

About the Author���������������������������������������������������������������������������������������������������������������� xv


About the Technical Reviewer������������������������������������������������������������������������������������������ xvii
Acknowledgments������������������������������������������������������������������������������������������������������������� xix
Preface������������������������������������������������������������������������������������������������������������������������������ xxi

■■Chapter 1: Introduction�����������������������������������������������������������������������������������������������������1
What’s All This, Then?��������������������������������������������������������������������������������������������������������������������2
What the book is about:����������������������������������������������������������������������������������������������������������������������������������������� 3
What the book covers only briefly or partially:������������������������������������������������������������������������������������������������������ 3
What the book isn’t about:������������������������������������������������������������������������������������������������������������������������������������� 3

Why Are You Here?������������������������������������������������������������������������������������������������������������������������3


Some Prerequisites�����������������������������������������������������������������������������������������������������������������������4
What’s in This Book�����������������������������������������������������������������������������������������������������������������������5
Summary���������������������������������������������������������������������������������������������������������������������������������������6
If You’re Curious … ����������������������������������������������������������������������������������������������������������������������6
Exercises���������������������������������������������������������������������������������������������������������������������������������������6
References������������������������������������������������������������������������������������������������������������������������������������7

■■Chapter 2: The Basics�������������������������������������������������������������������������������������������������������9


Some Core Ideas in Computing�����������������������������������������������������������������������������������������������������9
Asymptotic Notation��������������������������������������������������������������������������������������������������������������������10
It’s Greek to Me!�������������������������������������������������������������������������������������������������������������������������������������������������� 12
Rules of the Road������������������������������������������������������������������������������������������������������������������������������������������������ 14
Taking the Asymptotics for a Spin����������������������������������������������������������������������������������������������������������������������� 15

vii
■ Contents

Three Important Cases���������������������������������������������������������������������������������������������������������������������������������������� 18


Empirical Evaluation of Algorithms���������������������������������������������������������������������������������������������������������������������� 19

Implementing Graphs and Trees��������������������������������������������������������������������������������������������������22


Adjacency Lists and the Like������������������������������������������������������������������������������������������������������������������������������� 24
Adjacency Matrices��������������������������������������������������������������������������������������������������������������������������������������������� 27
Implementing Trees��������������������������������������������������������������������������������������������������������������������������������������������� 30
A Multitude of Representations��������������������������������������������������������������������������������������������������������������������������� 33
Beware of Black Boxes����������������������������������������������������������������������������������������������������������������34
Hidden Squares��������������������������������������������������������������������������������������������������������������������������������������������������� 35
The Trouble with Floats��������������������������������������������������������������������������������������������������������������������������������������� 36

Summary�������������������������������������������������������������������������������������������������������������������������������������38
If You’re Curious …���������������������������������������������������������������������������������������������������������������������39
Exercises�������������������������������������������������������������������������������������������������������������������������������������39
References����������������������������������������������������������������������������������������������������������������������������������40

■■Chapter 3: Counting 101�������������������������������������������������������������������������������������������������43


The Skinny on Sums��������������������������������������������������������������������������������������������������������������������43
More Greek���������������������������������������������������������������������������������������������������������������������������������������������������������� 44
Working with Sums��������������������������������������������������������������������������������������������������������������������������������������������� 44

A Tale of Two Tournaments����������������������������������������������������������������������������������������������������������45


Shaking Hands����������������������������������������������������������������������������������������������������������������������������������������������������� 45
The Hare and the Tortoise������������������������������������������������������������������������������������������������������������������������������������ 47

Subsets, Permutations, and Combinations����������������������������������������������������������������������������������50


Recursion and Recurrences��������������������������������������������������������������������������������������������������������53
Doing It by Hand�������������������������������������������������������������������������������������������������������������������������������������������������� 53
A Few Important Examples���������������������������������������������������������������������������������������������������������������������������������� 55
Guessing and Checking��������������������������������������������������������������������������������������������������������������������������������������� 58
The Master Theorem: A Cookie-Cutter Solution��������������������������������������������������������������������������������������������������� 60

So What Was All That About?�������������������������������������������������������������������������������������������������������63


Summary�������������������������������������������������������������������������������������������������������������������������������������64

viii
■ Contents

If You’re Curious ...����������������������������������������������������������������������������������������������������������������������65


Exercises�������������������������������������������������������������������������������������������������������������������������������������65
References����������������������������������������������������������������������������������������������������������������������������������66

■■Chapter 4: Induction and Recursion ... and Reduction����������������������������������������������������67


Oh, That’s Easy!���������������������������������������������������������������������������������������������������������������������������68
One, Two, Many����������������������������������������������������������������������������������������������������������������������������69
Mirror, Mirror�������������������������������������������������������������������������������������������������������������������������������71
Designing with Induction (and Recursion)�����������������������������������������������������������������������������������75
Finding a Maximum Permutation������������������������������������������������������������������������������������������������������������������������ 76
The Celebrity Problem����������������������������������������������������������������������������������������������������������������������������������������� 80
Topological Sorting���������������������������������������������������������������������������������������������������������������������������������������������� 82

Stronger Assumptions�����������������������������������������������������������������������������������������������������������������85
Invariants and Correctness���������������������������������������������������������������������������������������������������������86
Relaxation and Gradual Improvement�����������������������������������������������������������������������������������������87
Reduction + Contraposition = Hardness Proof����������������������������������������������������������������������������88
Problem Solving Advice���������������������������������������������������������������������������������������������������������������89
Summary�������������������������������������������������������������������������������������������������������������������������������������90
If You’re Curious ...����������������������������������������������������������������������������������������������������������������������90
Exercises�������������������������������������������������������������������������������������������������������������������������������������91
References����������������������������������������������������������������������������������������������������������������������������������92

■■Chapter 5: Traversal: The Skeleton Key of Algorithmics�������������������������������������������������93


A Walk in the Park�����������������������������������������������������������������������������������������������������������������������99
No Cycles Allowed��������������������������������������������������������������������������������������������������������������������������������������������� 100
How to Stop Walking in Circles�������������������������������������������������������������������������������������������������������������������������� 101

Go Deep!������������������������������������������������������������������������������������������������������������������������������������102
Depth-First Timestamps and Topological Sorting (Again)���������������������������������������������������������������������������������� 104

Infinite Mazes and Shortest (Unweighted) Paths����������������������������������������������������������������������106


Strongly Connected Components����������������������������������������������������������������������������������������������109
Summary�����������������������������������������������������������������������������������������������������������������������������������112
ix
■ Contents

If You’re Curious ...��������������������������������������������������������������������������������������������������������������������112


Exercises�����������������������������������������������������������������������������������������������������������������������������������112
References��������������������������������������������������������������������������������������������������������������������������������113

■■Chapter 6: Divide, Combine, and Conquer���������������������������������������������������������������������115


Tree-Shaped Problems: All About the Balance��������������������������������������������������������������������������115
The Canonical D&C Algorithm���������������������������������������������������������������������������������������������������117
Searching by Halves������������������������������������������������������������������������������������������������������������������118
Traversing Search Trees ... with Pruning����������������������������������������������������������������������������������������������������������� 120
Selection������������������������������������������������������������������������������������������������������������������������������������������������������������ 123

Sorting by Halves����������������������������������������������������������������������������������������������������������������������125
How Fast Can We Sort?������������������������������������������������������������������������������������������������������������������������������������� 127

Three More Examples����������������������������������������������������������������������������������������������������������������127


Closest Pair�������������������������������������������������������������������������������������������������������������������������������������������������������� 127
Convex Hull�������������������������������������������������������������������������������������������������������������������������������������������������������� 129
Greatest Slice���������������������������������������������������������������������������������������������������������������������������������������������������� 130

Tree Balance ... and Balancing*�������������������������������������������������������������������������������������������������131


Summary�����������������������������������������������������������������������������������������������������������������������������������136
If You’re Curious ...��������������������������������������������������������������������������������������������������������������������137
Exercises�����������������������������������������������������������������������������������������������������������������������������������137
References��������������������������������������������������������������������������������������������������������������������������������138
■■Chapter 7: Greed Is Good? Prove It! �����������������������������������������������������������������������������139
Staying Safe, Step by Step��������������������������������������������������������������������������������������������������������139
The Knapsack Problem��������������������������������������������������������������������������������������������������������������143
Fractional Knapsack������������������������������������������������������������������������������������������������������������������������������������������ 143
Integer Knapsack����������������������������������������������������������������������������������������������������������������������������������������������� 143

Huffman’s Algorithm������������������������������������������������������������������������������������������������������������������144
The Algorithm���������������������������������������������������������������������������������������������������������������������������������������������������� 145
The First Greedy Choice������������������������������������������������������������������������������������������������������������������������������������� 147
Going the Rest of the Way��������������������������������������������������������������������������������������������������������������������������������� 147
Optimal Merging������������������������������������������������������������������������������������������������������������������������������������������������ 148
x
■ Contents

Minimum Spanning Trees����������������������������������������������������������������������������������������������������������149


The Shortest Edge��������������������������������������������������������������������������������������������������������������������������������������������� 149
What About the Rest?���������������������������������������������������������������������������������������������������������������������������������������� 151
Kruskal’s Algorithm������������������������������������������������������������������������������������������������������������������������������������������� 151
Prim’s Algorithm������������������������������������������������������������������������������������������������������������������������������������������������ 153

Greed Works. But When?�����������������������������������������������������������������������������������������������������������155


Keeping Up with the Best���������������������������������������������������������������������������������������������������������������������������������� 155
No Worse Than Perfect�������������������������������������������������������������������������������������������������������������������������������������� 157
Staying Safe������������������������������������������������������������������������������������������������������������������������������������������������������ 157

Summary�����������������������������������������������������������������������������������������������������������������������������������159
If You’re Curious …�������������������������������������������������������������������������������������������������������������������160
Exercises�����������������������������������������������������������������������������������������������������������������������������������160
References��������������������������������������������������������������������������������������������������������������������������������161

■■Chapter 8: Tangled Dependencies and Memoization����������������������������������������������������163


Don’t Repeat Yourself����������������������������������������������������������������������������������������������������������������164
Shortest Paths in Directed Acyclic Graphs��������������������������������������������������������������������������������170
Longest Increasing Subsequence���������������������������������������������������������������������������������������������172
Sequence Comparison��������������������������������������������������������������������������������������������������������������175
The Knapsack Strikes Back�������������������������������������������������������������������������������������������������������178
Binary Sequence Partitioning����������������������������������������������������������������������������������������������������180
Summary�����������������������������������������������������������������������������������������������������������������������������������183
If You’re Curious …�������������������������������������������������������������������������������������������������������������������183
Exercises�����������������������������������������������������������������������������������������������������������������������������������184
References��������������������������������������������������������������������������������������������������������������������������������185

■■Chapter 9: From A to B with Edsger and Friends����������������������������������������������������������187


Propagating Knowledge������������������������������������������������������������������������������������������������������������188
Relaxing like Crazy��������������������������������������������������������������������������������������������������������������������189
Finding the Hidden DAG������������������������������������������������������������������������������������������������������������194
All Against All�����������������������������������������������������������������������������������������������������������������������������197

xi
■ Contents

Far-Fetched Subproblems���������������������������������������������������������������������������������������������������������198
Meeting in the Middle���������������������������������������������������������������������������������������������������������������201
Knowing Where You’re Going����������������������������������������������������������������������������������������������������203
Summary�����������������������������������������������������������������������������������������������������������������������������������206
If You’re Curious ...��������������������������������������������������������������������������������������������������������������������207
Exercises�����������������������������������������������������������������������������������������������������������������������������������207
References��������������������������������������������������������������������������������������������������������������������������������208

■■Chapter 10: Matchings, Cuts, and Flows ����������������������������������������������������������������������209


Bipartite Matching���������������������������������������������������������������������������������������������������������������������210
Disjoint Paths����������������������������������������������������������������������������������������������������������������������������212
Maximum Flow��������������������������������������������������������������������������������������������������������������������������215
Minimum Cut�����������������������������������������������������������������������������������������������������������������������������218
Cheapest Flow and the Assignment Problem*���������������������������������������������������������������������������219
Some Applications���������������������������������������������������������������������������������������������������������������������221
Summary�����������������������������������������������������������������������������������������������������������������������������������224
If You’re Curious …�������������������������������������������������������������������������������������������������������������������224
Exercises�����������������������������������������������������������������������������������������������������������������������������������224
References��������������������������������������������������������������������������������������������������������������������������������225

■■Chapter 11: Hard Problems and (Limited) Sloppiness��������������������������������������������������227


Reduction Redux�����������������������������������������������������������������������������������������������������������������������228
Not in Kansas Anymore?�����������������������������������������������������������������������������������������������������������230
Meanwhile, Back in Kansas …�������������������������������������������������������������������������������������������������232
But Where Do You Start? And Where Do You Go from There?����������������������������������������������������235
A Ménagerie of Monsters����������������������������������������������������������������������������������������������������������239
Return of the Knapsack������������������������������������������������������������������������������������������������������������������������������������� 239
Cliques and Colorings���������������������������������������������������������������������������������������������������������������������������������������� 240
Paths and Circuits���������������������������������������������������������������������������������������������������������������������������������������������� 242

When the Going Gets Tough, the Smart Get Sloppy�������������������������������������������������������������������245


Desperately Seeking Solutions��������������������������������������������������������������������������������������������������247
xii
■ Contents

And the Moral of the Story Is …�����������������������������������������������������������������������������������������������249


Summary�����������������������������������������������������������������������������������������������������������������������������������250
If You’re Curious …�������������������������������������������������������������������������������������������������������������������251
Exercises�����������������������������������������������������������������������������������������������������������������������������������251
References��������������������������������������������������������������������������������������������������������������������������������252

■■Appendix A: Pedal to the Metal: Accelerating Python���������������������������������������������������255


■■Appendix B: List of Problems and Algorithms���������������������������������������������������������������259
Problems�����������������������������������������������������������������������������������������������������������������������������������259
Algorithms and Data Structures������������������������������������������������������������������������������������������������262

■■Appendix C: Graph Terminology������������������������������������������������������������������������������������267


■■Appendix D: Hints for Exercises������������������������������������������������������������������������������������273
Chapter 1�����������������������������������������������������������������������������������������������������������������������������������273
Chapter 2�����������������������������������������������������������������������������������������������������������������������������������273
Chapter 3�����������������������������������������������������������������������������������������������������������������������������������275
Chapter 4�����������������������������������������������������������������������������������������������������������������������������������276
Chapter 5�����������������������������������������������������������������������������������������������������������������������������������278
Chapter 6�����������������������������������������������������������������������������������������������������������������������������������279
Chapter 7�����������������������������������������������������������������������������������������������������������������������������������280
Chapter 8�����������������������������������������������������������������������������������������������������������������������������������282
Chapter 9�����������������������������������������������������������������������������������������������������������������������������������283
Chapter 10���������������������������������������������������������������������������������������������������������������������������������284
Chapter 11���������������������������������������������������������������������������������������������������������������������������������285

Index���������������������������������������������������������������������������������������������������������������������������������289

xiii
About the Author

Magnus Lie Hetland is an experienced Python programmer, having used the


language since the late 1990s. He is also an associate professor of algorithms at the
Norwegian University of Science and Technology and has taught algorithms for
more than a decade. Hetland is the author of Beginning Python.

xv
About the Technical Reviewer

Stefan Turalski is just another coder who is perfectly happy delivering pragmatic,
not necessarily software, solutions and climbing the impassable learning curve.
He has more than a decade of experience building solutions in such diverse
domains as knowledge management, embedded networking, healthcare, power
and gas trading, and, in the last few years, finance.
Focusing on code optimization and systems integration, he has dabbled
(or almost drowned) in quite a few programming languages and has abused a number
of open source and commercial software frameworks, libraries, servers, and so on.
Stefan is currently working on a highly scalable, low-latency, intraday risk
valuation system at a financial institution in London. His latest interests revolve
around functional and reactive programming, F#, Clojure, Python, OpenCL,
and WebGL.
He still cannot believe that he was trusted enough to help on the second
edition of Magnus Lie Hetland’s superb book. Stefan hopes that his (and your) brain
cells injured while studying the algorithmic problems covered by the author will
recover stronger and wiser!

xvii
Acknowledgments

Thanks to everyone who contributed to this book, either directly or indirectly. This certainly includes my algorithm
mentors, Arne Halaas and Bjørn Olstad, as well as the entire crew at Apress and my brilliant tech editors, Alex Martelli
(for the first edition) and Stefan Turalski. Thanks to all the readers who pointed out errors in the first edition; I hope
I have corrected most of them. I’d especially like to thank Gerald Senarclens de Grancy, who supplied an extensive,
well-annotated list of errata covering the entire book. Thanks to Nils Grimsmo, Jon Marius Venstad, Ole Edsberg,
Rolv Seehuus, and Jorg Rødsjø for useful input; to my girlfriend, Janne Varvára Seem, my parents, Kjersti Lie and Tor
M. Hetland, and my sister, Anne Lie-Hetland, for their interest and support; and to my uncle Axel, for checking my
French. Finally, a big thank-you to the Python Software Foundation for their permission to reproduce parts of the
Python standard library and to Randall Munroe for letting me include some of his wonderful XKCD comics.

xix
Preface

This book is a marriage of three of my passions: algorithms, Python programming, and explaining things. To me, all
three of these are about aesthetics—finding just the right way of doing something, looking until you uncover a hint
of elegance, and then polishing that until it shines (or at least until it is a bit shinier). Of course, when there’s a lot of
material to cover, you may not get to polish things quite as much as you want. Luckily, though, most of the content in
this book is prepolished because I’m writing about really beautiful algorithms and proofs, as well as one of the cutest
programming languages out there. As for the third part, I’ve tried hard to find explanations that will make things seem
as obvious as possible. Even so, I’m sure I have failed in many ways, and if you have suggestions for improving the
book, I’d be happy to hear from you. Who knows, maybe some of your ideas could make it into a future edition. For
now, though, I hope you have fun with what’s here and that you take any newfound insight and run with it. If you can,
use it to make the world a more awesome place, in whatever way seems right.

xxi

Вам также может понравиться