




























































































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!





























































































Data Structures and
Algorithms with Python
123
Kent D. Lee Steve Hubbard Luther College Decorah, IA USA
ISSN 1863-7310 ISSN 2197-1781 (electronic) ISBN 978-3-319-13071-2 ISBN 978-3-319-13072-9 (eBook) DOI 10.1007/978-3-319-13072-
Library of Congress Control Number: 2014953918
Springer Cham Heidelberg New York Dordrecht London
© Springer International Publishing Switzerland 2015 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. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. 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.
Printed on acid-free paper
Springer is part of Springer Science+Business Media (www.springer.com)
Series editor Ian Mackie
Advisory Board Samson Abramsky, University of Oxford, Oxford, UK Karin Breitman, Pontifical Catholic University of Rio de Janeiro, Rio de Janeiro, Brazil Chris Hankin, Imperial College London, London, UK Dexter Kozen, Cornell University, Ithaca, USA Andrew Pitts, University of Cambridge, Cambridge, UK Hanne Riis Nielson, Technical University of Denmark, Kongens Lyngby, Denmark Steven Skiena, Stony Brook University, Stony Brook, USA Iain Stewart, University of Durham, Durham, UK
The text assumes that you have some prior experience in computer program- ming, probably from an introductory programming course where you learned to break simple problems into steps that could be solved by a computer. The language you used may have been Python, but not necessarily. Python is an excellent lan- guage for a text on data structures and algorithms whether you have used it before or not. Python is an object-oriented programming language with operator over- loading and dynamic typing. Whether this is your first exposure to Python or you used it in your first course, you will learn more about the language from this text. The first chapter of the text reviews some of the fundamentals of computer pro- gramming along with the basic syntax of Python to get you up to speed in the language. Then subsequent chapters dive into more advanced topics and should be read in sequence. At the beginning of every chapter the goals of the chapter are stated. At the end of every chapter is a set of review questions that reinforce the goals of the chapter. These review questions are followed in each chapter by a few programming problems that relate to the chapter goals by asking you to use the things you learned in the chapter and apply them to a computer program. You can motivate your reading of a chapter by first consulting the review questions and then reading the chapter to answer them. Along the way, there are lots of examples to illustrate the concepts being introduced. We hope you enjoy the text! If you have any questions or comments please send them to [email protected].
Kent D. Lee Steve Hubbard
vi Preface
A typical introductory data structures course covers the first seven chapters of this text. Chapter 1 introduces Python programming and the Tkinter module which is used in various places in the text. Tkinter comes with Python, so no special libraries need be installed for students to use it. Tkinter is used to visualize many of the results in this text. Chapter 2 introduces complexity analysis and depending on your needs, some of the material in Chap. 2 could be skipped in an introductory data structures course. In particular, the material on Θ notation and amortized complexity can be skipped. Big-Oh notation is enough for the first seven chapters. Typically, Chap. 7 is covered lightly and near the end of a semester course. It seems there is generally not enough time in a semester to cover graph theory in much detail. Advanced courses in data structures and algorithms should start with Chap. 1 if students are unfamiliar with Python or Tkinter. A brief refresher may not be bad even for those that have programmed using Python before. Chapter 2 should be covered in detail including the material on Θ notation and amortized complexity. Some review of hashing as it is used in sets and maps in Chap. 5 may be good review earlier in the advanced course along with a brief discussion of binary search trees and tree traversals in Chap. 6. Depending on your needs, Chap. 7 would be a good chapter to cover next including the material on depth first search of a graph. Chapter 8 is where the advanced material begins with assumptions made that students understand the concepts presented in the earlier chapters. The two introductory chapters along with Chaps. 8–12 make a seven-chapter sequence that will fill a semeseter in an advanced course nicely. This text is very project oriented. Solutions for all projects are available from Kent D. Lee. You can contact Kent at [email protected] for instructor solutions. You must provide proof (through a website or other reference) that you are an instructor at an educational institution to get access to the instructor materials.
vii
Connect Four is referenced in Chaps. 4, 12 and Appendix H. Connect Four is a trademark of the Milton Bradley Company in the United States and other countries. Chapter 2 references Mac OS X. Mac and Mac OS are registered trademarks of Apple Inc., registered in the U.S. and other countries. Microsoft Windows is also referenced in Chap. 2. Windows is a registered trademark of Microsoft Corporation in the United Stated and other countries.
ix
1
This Computer Science text further develops the skills you learned in your first CS text or course and adds to your bag of tricks by teaching you how to use efficient algorithms for dealing with large amounts of data. Without the proper understanding of efficiency, it is possible to bring even the fastest computers to a grinding halt when working with large data sets. This has happened before, and soon you will understand just how easy it can occur. But first, we’ll review some patterns for programming and look at the Python programming language to make sure you understand the basic structure and syntax of the language. To begin writing programs using Python you need to install Python on your com- puter. The examples in this text use Python 3. Python 2 is not compatible with Python 3 so you’ll want to be sure you have Python 3 or later installed on your computer. When writing programs in any language a good Integrated Development Environ- ment (IDE) is a valuable tool so you’ll want to install an IDE, too. Examples within this text will use Wing IDE 101 as pictured in Fig. 1.1, although other acceptable IDEs are available as well. The Wing IDE is well maintained, simple to use, and has a nice debugger which will be useful as you write Python programs. If you want to get Wing IDE 101 then go to http://wingware.com. The website http://cs.luther.edu/ ~leekent/CS1 has directions for installing both Python 3 and Wing IDE 101. Wing IDE 101 is the free version of Wing for educational use. There are some general concepts about Python that you should know when reading the text. Python is an interpreted language. That means that you don’t have to go through any extra steps after writing Python code before you can run it. You can simply press the debug button in the Wing IDE (it looks like an insect) and it will ask you to save your program if you haven’t already done so at least once. Then it will run your program. Python is also dynamically typed. This means that you will not get any type errors before you run your program as you would with some programming languages. It is especially important for you to understand the types of data you are using in your program. More on this in just a bit. Finally, your Python programs are interpreted by the Python interpreter. The shell is another name for the Python interpreter and Wing IDE 101 gives you access to a shell within the IDE
© Springer International Publishing Switzerland 2015 K.D. Lee and S. Hubbard, Data Structures and Algorithms with Python , Undergraduate Topics in Computer Science, DOI 10.1007/978-3-319-13072-9_
1
2 1 Python Programming 101
Fig. 1.1 The Wing IDE
itself. You can type Python statements and expressions into the window pane that says Python Shell to quickly try out a snippet of code before you put it in a program. Like most programming languages, there are a couple kinds of errors you can get in your Python programs. Syntax errors are found before your program runs. These are things like missing a colon or forgetting to indent something. An IDE like Wing IDE 101 will highlight these syntax errors so you can correct them. Run-time errors are found when your program runs. Run-time errors come from things like variables with unexpected values and operations on these values. To find a run-time error you can look at the Stack Data tab as it appears in Fig. 1.1. When a run-time error occurs the program will stop executing and the Stack Data tab will let you examine the run-time stack where you can see the program variables. In the event that you still don’t understand a problem, the Wing IDE 101 (and most other IDEs) lets you step through your code so you can watch as an error is reproduced. The three icons in the upper right corner of Fig. 1.1 let you Step Into a function, Step Over code, and Step Out Of a function, respectively. Stepping over or into your code can be valuable when trying to understand a run-time error and how it occurred. One other less than obvious tool is provided by the Wing IDE. By clicking on the line number on the left side of the IDE it is possible to set a breakpoint. A breakpoint causes the program to stop execution just before the breakpoint. From there it is possible to begin stepping over your code to determine how an error occurred.
4 1 Python Programming 101
Fig. 1.2 A Reference and Object
at objects. Any time you see an assignment statement, you should remember that the thing on the left side of the equals sign is a reference and the thing on the right side is either another reference or a newly created object. In this case, writing x = 6 makes a new object and then points x at this object. Other literal values may be written in Python as well. Here are some literal values that are possible in Python.
Python lets you specify float literals with an exponent. So, 4.5E10 represents the float 45000000000.0. Any number written with a deci- mal point is a float , whether there is a 0 or some other value after the decimal point. If you write a number using the E or exponent notation, it is a float as well. Any number without a decimal point is an int , unless it is written in E notation. String literals are surrounded by either single or double quotes. List literals are surrounded by [ and ]. The [] literal represents the empty list. The {} literal is the empty dictionary. You may not have previously used dictionaries. A dictionary is a mapping of keys to values. In the dictionary literal, the key ‘hi there’ is mapped to the value 6, and the key ‘how are you’ is mapped to 4. Dictionaries will be covered in some detail in Chap. 5.
Most of the time, when an object is created, it is not created from a literal value. Of course, we need literal values in programming languages, but most of the time we have an object already and want to create another object by using one or more existing objects. For instance, if we have a string in Python, like ‘6’ and want to create an int object from that string, we can do the following.
y = ’6’ x = int(y) print (x)
1.2 Creating Objects 5
In this short piece of code, y is a reference to the str object created from the string literal. The variable x is a reference to an object that is created by using the object that y refers to. In general, when we want to create an object based on other object values we write the following:
variable = type(other_object_values)
The type is any type or class name in Python, like int , float , str or any other type. The other_object_values is a comma-separated sequence of references to other objects that are needed by the class or type to create an instance (i.e. an object) of that type. Here are some examples of creating objects from non-literal values.
z = float(’6.3’) w = str(z) u = list(w)# this results in the list [’6’, ’.’, ’3’]
Objects are useful because they allow us to collect related information and group them with behavior that act on this data. These behaviors are called methods in Python. There are two kinds of methods in any object-oriented language: mutator and accessor methods. Accessor methods access the current state of an object but don’t change the object. Accessor methods return new object references when called.
x = ’how are you’ y = x.upper() print (y)
Here, the method upper is called on the object that x refers to. The upper accessor method returns a new object, a str object, that is an upper-cased version of the original string. Note that x is not changed by calling the upper method on it. The upper method is an accessor method. There are many accessor methods available on the str type which you can learn about in the appendices. Some methods are mutator methods. These methods actually change the existing object. One good example of this is the reverse method on the list type.
myList = [1, 2, 3] myList.reverse() print (myList)# This prints [3, 2, 1] to the screen
The reverse method mutates the existing object, in this case the list that myList refers to. Once called, a mutator method can’t be undone. The change or mutation is permanent until mutated again by some other mutator method. All classes contain accessor methods. Without accessor methods, the class would be pretty uninteresting. We use accessor methods to retrieve a value that is stored in an object or to retrieve a value that depends on the value stored in an object.