




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































■ Contents at a GlanCe
■ Appendix A: Pedal to the Metal: Accelerating Python ���������������������������������������������������
■ Appendix B: List of Problems and Algorithms���������������������������������������������������������������
■ Appendix C: Graph Terminology ������������������������������������������������������������������������������������
■ Appendix D: Hints for Exercises ������������������������������������������������������������������������������������
Chapter 1
Consider the following problem: You are to visit all the cities, towns, and villages of, say, Sweden and then return to your starting point. This might take a while (there are 24,978 locations to visit, after all), so you want to minimize your route. You plan on visiting each location exactly once, following the shortest route possible. As a programmer, you certainly don’t want to plot the route by hand. Rather, you try to write some code that will plan your trip for you. For some reason, however, you can’t seem to get it right. A straightforward program works well for a smaller number of towns and cities but seems to run forever on the actual problem, and improving the program turns out to be surprisingly hard. How come? Actually, in 2004, a team of five researchers^1 found such a tour of Sweden, after a number of other research teams had tried and failed. The five-man team used cutting-edge software with lots of clever optimizations and tricks of the trade, running on a cluster of 96 Xeon 2.6GHz workstations. Their software ran from March 2003 until May 2004, before it finally printed out the optimal solution. Taking various interruptions into account, the team estimated that the total CPU time spent was about 85 years! Consider a similar problem: You want to get from Kashgar, in the westernmost region of China, to Ningbo, on the east coast, following the shortest route possible.^2 Now, China has 3,583,715 km of roadways and 77,834 km of railways, with millions of intersections to consider and a virtually unfathomable number of possible routes to follow. It might seem that this problem is related to the previous one, yet this shortest path problem is one solved routinely, with no appreciable delay, by GPS software and online map services. If you give those two cities to your favorite map service, you should get the shortest route in mere moments. What’s going on here? You will learn more about both of these problems later in the book; the first one is called the traveling salesman (or salesrep ) problem and is covered in Chapter 11, while so-called shortest path problems are primarily dealt with in Chapter 9. I also hope you will gain a rather deep insight into why one problem seems like such a hard nut to crack while the other admits several well-known, efficient solutions. More importantly, you will learn something about how to deal with algorithmic and computational problems in general, either solving them efficiently, using one of the several techniques and algorithms you encounter in this book, or showing that they are too hard and that approximate solutions may be all you can hope for. This chapter briefly describes what the book is about—what you can expect and what is expected of you. It also outlines the specific contents of the various chapters to come in case you want to skip around.
(^1) David Applegate, Robert Bixby, Vašek Chvátal, William Cook, and Keld Helsgaun (^2) Let’s assume that flying isn’t an option.
Chapter 1 ■ IntroduCtIon
What the book is about:
What the book covers only briefly or partially:
What the book isn’t about:
As you can see, “implementing things in Python” is just part of the picture. The design principles and theoretical foundations are included in the hope that they’ll help you design your own algorithms and data structures.
Why Are You Here?
When working with algorithms, you’re trying to solve problems efficiently. Your programs should be fast; the wait for a solution should be short. But what, exactly, do I mean by efficient, fast, and short? And why would you care about these things in a language such as Python, which isn’t exactly lightning-fast to begin with? Why not rather switch to, say, C or Java? First, Python is a lovely language, and you may not want to switch. Or maybe you have no choice in the matter. But second, and perhaps most importantly, algorists don’t primarily worry about constant differences in performance.^4 If one program takes twice, or even ten times, as long as another to finish, it may still be fast enough , and the slower program (or language) may have other desirable properties, such as being more readable. Tweaking and optimizing can be costly in many ways and is not a task to be taken on lightly. What does matter, though, no matter the language, is how your program scales. If you double the size of your input, what happens? Will your program run for twice as long? Four times? More? Will the running time double even if you add just one measly bit to the input? These are the kind of differences that will easily trump language or hardware choice, if your problems get big enough. And in some cases “big enough” needn’t be all that big. Your main weapon in whittling down the growth of your running time is—you guessed it—a solid understanding of algorithm design. Let’s try a little experiment. Fire up an interactive Python interpreter, and enter the following:
count = 10** nums = [] for i in range(count): ... nums.append(i) ... nums.reverse()
(^4) I’m talking about constant multiplicative factors here, such as doubling or halving the execution time.
Chapter 1 ■ IntroduCtIon
Not the most useful piece of code, perhaps. It simply appends a bunch of numbers to an (initially) empty list and then reverses that list. In a more realistic situation, the numbers might come from some outside source (they could be incoming connections to a server, for example), and you want to add them to your list in reverse order, perhaps to prioritize the most recent ones. Now you get an idea: instead of reversing the list at the end, couldn’t you just insert the numbers at the beginning, as they appear? Here’s an attempt to streamline the code (continuing in the same interpreter window):
nums = [] for i in range(count): ... nums.insert(0, i)
Unless you’ve encountered this situation before, the new code might look promising, but try to run it. Chances are you’ll notice a distinct slowdown. On my computer, the second piece of code takes around 200 times as long as the first to finish.^5 Not only is it slower, but it also scales worse with the problem size. Try, for example, to increase count from 105 to 106. As expected, this increases the running time for the first piece of code by a factor of about ten … but the second version is slowed by roughly two orders of magnitude, making it more than two thousand times slower than the first! As you can probably guess, the discrepancy between the two versions only increases as the problem gets bigger, making the choice between them ever more crucial.
Some Prerequisites
This book is intended for two groups of people: Python programmers, who want to beef up their algorithmics, and students taking algorithm courses, who want a supplement to their plain-vanilla algorithms textbook. Even if you belong to the latter group, I’m assuming you have a familiarity with programming in general and with Python in particular. If you don’t, perhaps my book Beginning Python can help? The Python web site also has a lot of useful material, and Python is a really easy language to learn. There is some math in the pages ahead, but you don’t have to be a math prodigy to follow the text. You’ll be dealing with some simple sums and nifty concepts such as polynomials, exponentials, and logarithms, but I’ll explain it all as we go along. Before heading off into the mysterious and wondrous lands of computer science, you should have your equipment ready. As a Python programmer, I assume you have your own favorite text/code editor or integrated development environment—I’m not going to interfere with that. When it comes to Python versions, the book is written to be reasonably version-independent, meaning that most of the code should work with both the Python 2 and 3 series. Where backward-incompatible Python 3 features are used, there will be explanations on how to implement the algorithm in Python 2 as well. (And if, for some reason, you’re still stuck with, say, the Python 1.5 series, most of the code should still work, with a tweak here and there.)
(^5) See Chapter 2 for more on benchmarking and empirical evaluation of algorithms.
Chapter 1 ■ IntroduCtIon
Chapter 11: Hard Problems and (Limited) Sloppiness. As alluded to in the beginning of the introduction, there are problems we don’t know how to solve efficiently and that we have reasons to think won’t be solved for a long time— maybe never. In this chapter, you learn how to apply the trusty tool of reduction in a new way: not to solve problems but to show that they are hard. Also, we take a look at how a bit of (strictly limited) sloppiness in the optimality criteria can make problems a lot easier to solve.
Appendix A: Pedal to the Metal: Accelerating Python. The main focus of this book is asymptotic efficiency—making your programs scale well with problem size. However, in some cases, that may not be enough. This appendix gives you some pointers to tools that can make your Python programs go faster. Sometimes a lot (as in hundreds of times) faster.
Appendix B: List of Problems and Algorithms. This appendix gives you an overview of the algorithmic problems and algorithms discussed in the book, with some extra information to help you select the right algorithm for the problem at hand.
Appendix C: Graph Terminology and Notation. Graphs are a really useful structure, both in describing real-world systems and in demonstrating how various algorithms work. This chapter gives you a tour of the basic concepts and lingo, in case you haven’t dealt with graphs before.
Appendix D: Hints for Exercises. Just what the title says.
Summary
Programming isn’t just about software architecture and object-oriented design; it’s also about solving algorithmic problems, some of which are really hard. For the more run-of-the-mill problems (such as finding the shortest path from A to B), the algorithm you use or design can have a huge impact on the time your code takes to finish, and for the hard problems (such as finding the shortest route through A–Z), there may not even be an efficient algorithm, meaning that you need to accept approximate solutions. This book will teach you several well-known algorithms, along with general principles that will help you create your own. Ideally, this will let you solve some of the more challenging problems out there, as well as create programs that scale gracefully with problem size. In the next chapter, we get started with the basic concepts of algorithmics, dealing with terms that will be used throughout the entire book.
If You’re Curious …
This is a section you’ll see in all the chapters to come. It’s intended to give you some hints about details, wrinkles, or advanced topics that have been omitted or glossed over in the main text and to point you in the direction of further information. For now, I’ll just refer you to the “References” section, later in this chapter, which gives you details about the algorithm books mentioned in the main text.
Exercises
As with the previous section, this is one you’ll encounter again and again. Hints for solving the exercises can be found in Appendix D. The exercises often tie in with the main text, covering points that aren’t explicitly discussed there but that may be of interest or that deserve some contemplation. If you want to really sharpen your algorithm design skills, you might also want to check out some of the myriad of sources of programming puzzles out there. There are, for example, lots of programming contests (a web search should turn up plenty), many of which post problems that you can play with. Many big software companies also have qualification tests based on problems such as these and publish some of them online.
Chapter 1 ■ IntroduCtIon
Because the introduction doesn’t cover that much ground, I’ll just give you a couple of exercises here—a taste of what’s to come:
1-1. Consider the following statement: “As machines get faster and memory cheaper, algorithms become less important.” What do you think; is this true or false? Why?
1-2. Find a way of checking whether two strings are anagrams of each other (such as "debit card" and "bad credit"). How well do you think your solution scales? Can you think of a naïve solution that will scale poorly?
References
Applegate, D., Bixby, R., Chvátal, V., Cook, W., and Helsgaun, K. Optimal tour of Sweden. www.math.uwaterloo.ca/tsp/sweden/. Accessed April 6, 2014.
Cormen, T. H., Leiserson, C. E., Rivest, R. L., and Stein, C. (2009). Introduction to Algorithms , second edition. MIT Press.
Dasgupta, S., Papadimitriou, C., and Vazirani, U. (2006). Algorithms. McGraw-Hill.
Goodrich, M. T. and Tamassia, R. (2001). Algorithm Design: Foundations, Analysis, and Internet Examples. John Wiley & Sons, Ltd.
Hetland, M. L. (2008). Beginning Python: From Novice to Professional , second edition. Apress.
Kleinberg, J. and Tardos, E. (2005). Algorithm Design. Addison-Wesley Longman Publishing Co., Inc.
Knuth, D. E. (1968). Fundamental Algorithms, volume 1 of The Art of Computer Programming. Addison-Wesley.
———. (1969). Seminumerical Algorithms, volume 2 of The Art of Computer Programming. Addison-Wesley.
———. (1973). Sorting and Searching , volume 3 of The Art of Computer Programming. Addison-Wesley.
———. (2011). Combinatorial Algorithms, Part 1 , volume 4A of The Art of Computer Programming. Addison-Wesley.
Miller, B. N. and Ranum, D. L. (2005). Problem Solving with Algorithms and Data Structures Using Python. Franklin Beedle & Associates.
Chapter 2 ■ the BasiCs
the formalism is often used when discussing which problems can be solved (either at all or in reasonable time, as discussed later in this chapter and in Chapter 11). For more fine-grained analysis of algorithmic efficiency, however, Turing machines are not usually the first choice. Instead of scrolling along a paper tape, we use a big chunk of memory that can be accessed directly. The resulting machine is commonly known as the random-access machine. While the formalities of the random-access machine can get a bit complicated, we just need to know something about the limits of its capabilities so we don’t cheat in our algorithm analyses. The machine is an abstract, simplified version of a standard, single-processor computer, with the following properties:
In some cases, we may need to be more specific, but this machine sketch should do for the moment. We now have a bit of an intuition for what algorithms are, as well as the abstract hardware we’ll be running them on. The last piece of the puzzle is the notion of a problem. For our purposes, a problem is a relation between input and output. This is, in fact, much more precise than it might sound: A relation, in the mathematical sense, is a set of pairs—in our case, which outputs are acceptable for which inputs—and by specifying this relation, we’ve got our problem nailed down. For example, the problem of sorting may be specified as a relation between two sets, A and B, each consisting of sequences.^3 Without describing how to perform the sorting (that would be the algorithm), we can specify which output sequences (elements of B) that would be acceptable, given an input sequence (an element of A). We would require that the result sequence consisted of the same elements as the input sequence and that the elements of the result sequence were in increasing order (each bigger than or equal to the previous). The elements of A here—that is, the inputs—are called problem instances ; the relation itself is the actual problem. To get our machine to work with a problem, we need to encode the input as zeros and ones. We won’t worry too much about the details here, but the idea is important, because the notion of running time complexity (as described in the next section) is based on knowing how big a problem instance is, and that size is simply the amount of memory needed to encode it. As you’ll see, the exact nature of this encoding usually won’t matter.
Asymptotic Notation
Remember the append versus insert example in Chapter 1? Somehow, adding items to the end of a list scaled better with the list size than inserting them at the front; see the nearby “Black Box” sidebar on list for an explanation. These built-in operations are both written in C, but assume for a minute that you reimplement list.append in pure Python; let’s say arbitrarily that the new version is 50 times slower than the original. Let’s also say you run your slow, pure-Python append-based version on a really slow machine, while the fast, optimized, insert-based version is run on a computer that is 1,000 times faster. Now the speed advantage of the insert version is a factor of 50,000. You compare the two implementations by inserting 100,000 numbers. What do you think happens? Intuitively, it might seem obvious that the speedy solution should win, but its “speediness” is just a constant factor, and its running time grows faster than the “slower” one. For the example at hand, the Python-coded version running on the slower machine will, actually, finish in half the time of the other one. Let’s increase the problem size a bit, to 10 million numbers, for example. Now the Python version on the slow machine will be 2,000 times faster than the C version on the fast machine. That’s like the difference between running for about a minute and running almost a day and a half!
(^3) Because input and output are of the same type, we could actually just specify a relation between A and A.
Chapter 2 ■ the BasiCs
This distinction between constant factors (related to such things as general programming language performance and hardware speed, for example) and the growth of the running time, as problem sizes increase, is of vital importance in the study of algorithms. Our focus is on the big picture—the implementation-independent properties of a given way of solving a problem. We want to get rid of distracting details and get down to the core differences, but in order to do so, we need some formalism.
class Node: def init(self, value, next=None): self.value = value self.next = next
L = Node("a", Node("b", Node("c", Node("d")))) L.next.next.value 'c'
(^4) For an “out-of-the-box” solution for inserting objects at the beginning of a sequence, see the black-box sidebar on deque
in Chapter 5.
Chapter 2 ■ the BasiCs
This is a fairly straightforward and understandable definition, although it may seem a bit foreign at first. Basically, O ( g ) is the set of functions that do not grow faster than g. For example, the function n^2 is in the set O ( n^2 ), or, in set notation, n^2 ∈ O ( n^2 ). We often simply say that n^2 is O ( n^2 ). The fact that n^2 does not grow faster than itself is not particularly interesting. More useful, perhaps, is the fact that neither 2.4 n^2 + 7 nor the linear function n does. That is, we have both
2.4 n^2 + 7 ∈ O ( n^2 )
and
n ∈ O ( n^2 ).
The first example shows us that we are now able to represent a function without all its bells and whistles; we can drop the 2.4 and the 7 and simply express the function as O ( n^2 ), which gives us just the information we need. The second shows us that O can be used to express loose limits as well: Any function that is better (that is, doesn’t grow faster) than g can be found in O ( g ). How does this relate to our original example? Well, the thing is, even though we can’t be sure of the details (after all, they depend on both the Python version and the hardware you’re using), we can describe the operations asymptotically: The running time of appending n numbers to a Python list is O ( n ), while inserting n numbers at its beginning is O ( n^2 ). The other two, W and Q, are just variations of O. W is its complete opposite: A function f is in W( g ) if it satisfies the following condition: There exists a natural number n 0 and a positive constant c such that
f ( n ) ³ cg ( n )
for all n ³ n 0. So, where O forms a so-called asymptotic upper bound, W forms an asymptotic lower bound.
The sets formed by Q are simply intersections of the other two, that is, Q( g ) = O ( g ) ∩ W( g ). In other words, a function f is in Q( g ) if it satisfies the following condition: There exists a natural number n 0 and two positive constants c 1 and c 2 such that
c 1 g ( n ) £ f ( n ) £ c 2 g ( n )
for all n ³ n 0. This means that f and g have the same asymptotic growth. For example, 3 n^2 + 2 is Q( n^2 ), but we could just as well write that n^2 is Q(3 n^2 + 2). By supplying an upper bound and a lower bound at the same time, the Q operator is the most informative of the three, and I will use it when possible.
cn^2
T (n )
n 0
Figure 2-1. For values of n greater than n 0 , T(n) is less than cn^2 , so T(n) is O(n^2 )
Chapter 2 ■ the BasiCs
Rules of the Road
While the definitions of the asymptotic operators can be a bit tough to use directly, they actually lead to some of the simplest math ever. You can drop all multiplicative and additive constants, as well as all other “small parts” of your function, which simplifies things a lot. As a first step in juggling these asymptotic expressions, let’s take a look at some typical asymptotic classes, or orders. Table 2-1 lists some of these, along with their names and some typical algorithms with these asymptotic running times, also sometimes called running-time complexities. (If your math is a little rusty, you could take a look at the sidebar “A Quick Math Refresher” later in the chapter.) An important feature of this table is that the complexities have been ordered so that each row dominates the previous one: If f is found higher in the table than g , then f is O ( g ).^5
Table 2-1. Common Examples of Asymptotic Running Times
Q(1) Constant Hash table lookup and modification (see “Black Box” sidebar on dict).
Q(lg n ) Logarithmic Binary search (see Chapter 6). Logarithm base unimportant.^7
Q( n ) Linear Iterating over a list.
Q( n lg n ) Loglinear Optimal sorting of arbitrary values (see Chapter 6). Same as Q(lg n !).
Q( n^2 ) Quadratic Comparing n objects to each other (see Chapter 3).
Q( n^3 ) Cubic Floyd and Warshall’s algorithms (see Chapters 8 and 9).
O ( nk ) Polynomial k nested for loops over n (if k is a positive integer). For any constant k > 0.
W( kn ) Exponential Producing every subset of n items ( k = 2; see Chapter 3). Any k > 1.
Q( n !) Factorial Producing every ordering of n values.
Any polynomial (that is, with any power k > 0, even a fractional one) dominates any logarithm (that is, with any base), and any exponential (with any base k > 1) dominates any polynomial (see Exercises 2-5 and 2-6). Actually, all logarithms are asymptotically equivalent—they differ only by constant factors (see Exercise 2-4). Polynomials and exponentials, however, have different asymptotic growth depending on their exponents or bases, respectively. So, n^5 grows faster than n^4 , and 5 n^ grows faster than 4 n. The table primarily uses Q notation, but the terms polynomial and exponential are a bit special, because of the role they play in separating tractable (“solvable”) problems from intractable (“unsolvable”) ones, as discussed in Chapter 11. Basically, an algorithm with a polynomial running time is considered feasible, while an exponential one is generally useless. Although this isn’t entirely true in practice, (Q( n^100 ) is no more practically useful than Q(2 n )); it is, in many cases, a useful distinction.^6 Because of this division, any running time in O ( nk ), for any k > 0,
(^5) For the “Cubic” and “Polynomial” row, this holds only when k ³ 3. (^6) Interestingly, once a problem is shown to have a polynomial solution, an efficient polynomial solution can quite often be
found as well. (^7) I’m using lg rather than log here, but either one is fine.
Chapter 2 ■ the BasiCs
We know that the line first takes constant time. At the time we get to the second line, the list size has changed and is now n + 1. This means that the complexity of the second line is Q( n + 1), which is the same as Q( n ). Thus, the total running time is the sum of the two complexities, Q(1) + Q( n ) = Q( n ). Now, let’s consider some simple loops. Here’s a plain for loop over a sequence with n elements (numbers, say; for example, seq = range(n)):^8
s = 0 for x in seq: s += x
This is a straightforward implementation of what the sum function does: It iterates over seq and adds the elements to the starting value in s. This performs a single constant-time operation (s += x) for each of the n elements of seq, which means that its running time is linear, or Q( n ). Note that the constant-time initialization (s = 0 ) is dominated by the loop here. The same logic applies to the “camouflaged” loops we find in list (or set or dict) comprehensions and generator expressions, for example. The following list comprehension also has a linear running-time complexity:
squares = [x**2 for x in seq]
Several built-in functions and methods also have “hidden” loops in them. This generally applies to any function or method that deals with every element of a container, such as sum or map, for example. Things get a little bit (but not a lot) trickier when we start nesting loops. Let’s say we want to sum up all possible products of the elements in seq; here’s an example:
s = 0 for x in seq: for y in seq: s += x*y
One thing worth noting about this implementation is that each product will be added twice. If 42 and 333 are both in seq, for example, we’ll add both 42333 and 33342. That doesn’t really affect the running time; it’s just a constant factor. What’s the running time now? The basic rule is easy: The complexities of code blocks executed one after the other are just added. The complexities of nested loops are multiplied. The reasoning is simple: For each round of the outer loop, the inner one is executed in full. In this case, that means “linear times linear,” which is quadratic. In other words, the running time is Q( n · n ) = Q( n^2 ). Actually, this multiplication rule means that for further levels of nesting, we will just increment the power (that is, the exponent). Three nested linear loops give us Q( n^3 ), four give us Q( n^4 ), and so forth. The sequential and nested cases can be mixed, of course. Consider the following slight extension:
s = 0 for x in seq: for y in seq: s += x*y for z in seq: for w in seq: s += x-w
(^8) If the elements are ints, the running time of each += is constant. However, Python also support big integers, or longs, which
automatically appear when your integers get big enough. This means you can break the constant-time assumption by using really huge numbers. If you’re using floats, that won’t happen (but see the discussion of float problems near the end of the chapter).
Chapter 2 ■ the BasiCs
It may not be entirely clear what we’re computing here (I certainly have no idea), but we should still be able to find the running time, using our rules. The z-loop is run for a linear number of iterations, and it contains a linear loop, so the total complexity there is quadratic, or Q( n^2 ). The y-loop is clearly Q( n ). This means that the code block inside the x-loop is Q( n + n^2 ). This entire block is executed for each round of the x-loop, which is run n times. We use our multiplication rule and get Q( n ( n + n^2 )) = Q( n^2 + n^3 ) = Q( n^3 ), that is, cubic. We could arrive at this conclusion even more easily by noting that the y-loop is dominated by the z-loop and can be ignored, giving the inner block a quadratic running time. “Quadratic times linear” gives us cubic. The loops need not all be repeated Q( n ) times, of course. Let’s say we have two sequences, seq1 and seq2, where seq1 contains n elements and seq2 contains m elements. The following code will then have a running time of Q( nm ).
s = 0 for x in seq1: for y in seq2: s += x*y
In fact, the inner loop need not even be executed the same number of times for each iteration of the outer loop. This is where things can get a bit fiddly. Instead of just multiplying two iteration counts, such as n and m in the previous example, we now have to sum the iteration counts of the inner loop. What that means should be clear in the following example:
seq1 = [[0, 1], [2], [3, 4, 5]] s = 0 for seq2 in seq1: for x in seq2: s += x
The statement s += x is now performed 2 + 1 + 3 = 6 times. The length of seq2 gives us the running time of the inner loop, but because it varies, we cannot simply multiply it by the iteration count of the outer loop. A more realistic example is the following, which revisits our original example—multiplying every combination of elements from a sequence:
s = 0 n = len(seq) for i in range(n-1): for j in range(i+1, n): s += seq[i] * seq[j]
To avoid multiplying objects with themselves or adding the same product twice, the outer loop now avoids the last item, and the inner loop iterates over the items only after the one currently considered by the outer one. This is actually a lot less confusing than it might seem, but finding the complexity here requires a little bit more care. This is one of the important cases of counting that is covered in the next chapter.^9
(^9) Spoiler: The complexity of this example is still Q( n (^2) ).