id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
14,400 | ( ( ) (nthere exists and such that ( < (nfor all omega notationo the notation (nis the formal way to express the lower bound of an algorithm' running time it measures the best case time complexity or the best amount of time an algorithm can possibly take to complete for examplefor function (no( ( )> (nthere exists and ... |
14,401 | thanks for choosing data structures and algorithms with python this text was written based on classroom notes for two coursesan introductory data structures and algorithms course and an advanced data structures and algorithms course the material contained in this text can be taught in two semesters the early in this te... |
14,402 | preface the text assumes that you have some prior experience in computer programmingprobably from an introductory programming course where you learned to break simple problems into steps that could be solved by computer the language you used may have been pythonbut not necessarily python is an excellent language for te... |
14,403 | typical introductory data structures course covers the first seven of this text introduces python programming and the tkinter module which is used in various places in the text tkinter comes with pythonso no special libraries need be installed for students to use it tkinter is used to visualize many of the results in t... |
14,404 | for teachers if you have any suggestions or find any errors in the textplease let us know by emailing kent at kentdlee@luther edu thanks and we hope you enjoy using the text in your coursekent lee steve hubbard this copy belongs to 'acha |
14,405 | connect four is referenced in chaps and appendix connect four is trademark of the milton bradley company in the united states and other countries references mac os mac and mac os are registered trademarks of apple inc registered in the and other countries microsoft windows is also referenced in chap windows is register... |
14,406 | python programming goals creating objects calling methods on objects implementing class operator overloading importing modules indentation in python programs the main function reading from file reading multi-line records from file container class polymorphism the accumulator pattern implementing gui with tkinter xml fi... |
14,407 | contents making the pylist append efficient commonly occurring computational complexities more asymptotic notation amortized complexity summary review questions programming problems recursion goals scope the run-time stack and the heap writing recursive function tracing the execution of recursive function recursion in ... |
14,408 | xiii maps memoization correlating two sources of information summary review questions programming problems trees goals abstract syntax trees and expressions prefix and postfix expressions parsing prefix expressions binary search trees search spaces summary review questions programming problems graphs goals graph notati... |
14,409 | contents phase ii analysis of phase ii the heapsort algorithm version analysis of heapsort version comparison to other sorting algorithms summary review questions programming problems balanced binary search trees goals binary search trees avl trees splay trees iterative splaying recursive splaying performance analysis ... |
14,410 | xv appendix ainteger operators appendix bfloat operators appendix cstring operators and methods appendix dlist operators and methods appendix edictionary operators and methods appendix fturtle methods appendix gturtlescreen methods appendix hcomplete programs the draw program the scope program the sort animation the pl... |
14,411 | python programming 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 efficiencyit is possible to bring even the faste... |
14,412 | python programming fig the wing ide itself you can type python statements and expressions into the window pane that says python shell to quickly try out snippet of code before you put it in program like most programming languagesthere are couple kinds of errors you can get in your python programs syntax errors are foun... |
14,413 | python programming to motivate learning or reviewing python in this the text will develop simple drawing application using turtle graphics and graphical user interface (guiframework called tkinter along the wayyou'll discover some patterns for programming including the accumulator pattern and the loop and half pattern ... |
14,414 | python programming fig reference and object at objects any time you see an assignment statementyou should remember that the thing on the left side of the equals sign is reference and the thing on the right side is either another reference or newly created object in this casewriting makes new object and then points at t... |
14,415 | in this short piece of codey is reference to the str object created from the string literal the variable is reference to an object that is created by using the object that refers to in generalwhen we want to create an object based on other object values we write the followingvariable type(other_object_valuesthe type is... |
14,416 | python programming if class had no accessor methods we could put values in the object but we could never retrieve them some classes have mutator methods and some don' for instancethe list class has mutator methodsincluding the reverse method there are some classes that don' have any mutator methods for instancethe str ... |
14,417 | fig couple of dog objects python takes care of passing the self argument to the methods the other arguments are passed by the programmer when the method is called (see the example of calling each method in sect the dog class class dogthis is the constructor for the class it is called whenever dog object is created the ... |
14,418 | python programming return self name this is another accessor method that uses the birthday information to return string representing the date def birthdate(self)return str(self month"/str(self day"/str(self year this is mutator method that changes the speaktext of the dog object def changebark(self,bark)self speaktext ... |
14,419 | def __init__(selfnamemonthdayyearspeaktext)self name name self month month self day day self year year self speaktext speaktext this is an accessor method that returns the speaktext stored in the object notice that "selfis parameter every method has "selfas its first parameter the "selfparameter is reference to the cur... |
14,420 | python programming method defintion __add__(self,yoperator + __contains__(self,y__eq__(self,y__ge__(self,y__getitem__(self,y__gt__(self,y__hash__(self__int__(self__iter__(self__le__(self,y__len__(self__lt__(self,y__mod__(self,y__mul__(self,y__ne__(self,y__neg__(self__repr__(selfy in = > [yx> hash(xint(xfor in < len(xx<... |
14,421 | remains useful way of thinking about computer graphics the idea is that turtle is wandering beach and as it walks around it drags its tail in the sand leaving trail behind it all that you can do with turtle is discussed in the chap there are two ways to import module in pythonthe convenient way and the safe way which w... |
14,422 | python programming fig adjusting indentation in wing ide the main function programs are typically written with many function definitions and function calls one function definition is written by convention in pythonusually called the main function this function contains code the program typically executes when it is fir... |
14,423 | program is run as stand-alone program sometimes we write modules that we may want to import into another module writing this if statement to call the main function makes the module execute its own main function when it is run as stand-alone program when the module is imported into another module it will not execute its... |
14,424 | python programming goto black endfill to process the records in the file in sect we can write python program that reads the lines of this file and does the appropriate turtle graphics commands for each record in the file since each record ( drawing commandis on its own line in the file format described in sect we can r... |
14,425 | goto( ,yelif command ="circle"radius float(commandlist[ ]width float(commandlist[ ]color commandlist[ strip( width(widtht pencolor(colort circle(radiuselif command ="beginfill"color commandlist[ strip( fillcolor(colort begin_fill(elif command ="endfill" end_fill(elif command ="penup" penup(elif command ="pendown" pendo... |
14,426 | python programming terminates if you do not close it explicitly file close( reading multi-line records from file sometimes records of file are not one per line records of file may cross multiple lines in that caseyou can' use for loop to read the file you need while loop instead when you use while loopyou need to be ab... |
14,427 | black pendown beginfill yellow goto - black goto - black goto black goto black goto black goto black goto black goto black endfill to read file as shown in sect we write our loop and half to read the first line of each record and then check that line ( the graphics commandso we know how many more lines to read the code... |
14,428 | python programming reading and processing multi-line records import turtle def main()filename input("please enter drawing filename" turtle turtle(screen getscreen( file open(filename" " here we have the half loop to get things started reading our first graphics command here lets us determine if the file is empty or not... |
14,429 | close the file file close( ht(screen exitonclick(print("program execution completed " if __name__ ="__main__"main(when reading file with multi-line recordsa while loop is needed notice that on line the first line of the first record is read prior to the while loop for the body of the while loop to executethe condition ... |
14,430 | python programming container class to further enhance our drawing program we will first create data structure to hold all of our drawing commands this is our first example of defining our own class in this text so we'll go slow and provide lot of detail about what is happening and why to begin let' figure out what we w... |
14,431 | graphics command classes each of the command classes below hold information for one of the types of commands found in graphics file for each command there must be draw method that is given turtle and uses the turtle to draw the object by having draw method for each classwe can polymorphically call the right draw method... |
14,432 | python programming class pendowncommanddef __init__(self)pass def draw(self,turtle)turtle pendown( the accumulator pattern to use the different command classes that we have just definedour program will read the variable length records from the file as it did before using the loop and half pattern that we have already s... |
14,433 | this is our pylist class it holds list of our graphics commands class pylistdef __init__(self)self items [ def append(self,item)self items self items [item if we want to iterate over this sequencewe define the special method called __iter__(selfwithout this we'll get "builtins typeerror'pylistobject is not iterableif w... |
14,434 | python programming cmd beginfillcommand(color elif command ="endfill"cmd endfillcommand( elif command ="penup"cmd penupcommand( elif command ="pendown"cmd pendowncommand(elseraising an exception will terminate the program immediately which is what we want to happen if we encounter an unknown command the runtimeerror ex... |
14,435 | fig the draw program to construct gui you need to create window it is really very simple to do this using tkinter root tkinter tk(this creates an empty window on the screenbut of course does not put anything in it we need to place widgets in it so it looks like the window in fig (without the nice picture that denise dr... |
14,436 | python programming fig the draw program layout the drawingapplication frame inherits from frame when programming in an object-oriented languagesometimes you want to implement classbut it is almost like another class in this casethe drawingapplication is frame this means there are two parts to drawingapplication objects... |
14,437 | in addition to the event handlers for the widgetsthere are three other event handlers the onclick event occurs when you click the mouse button on the canvas the ondrag event handler occurs when the turtle is dragged around the canvas finallythe undohandler is called when the key is pressed on the keyboard gui drawing a... |
14,438 | python programming float(attr[" "valuey float(attr[" "valuewidth float(attr["width"valuecolor attr["color"value strip(cmd gotocommand( , ,width,color elif command ="circle"radius float(attr["radius"valuewidth float(attr["width"valuecolor attr["color"value strip(cmd circlecommand(radius,width,color elif command ="beginf... |
14,439 | screen update( filemenu add_command(label="load into ",command=addtofile the write function writes an xml file to the given filename def write(filename)file open(filename" "file write('\ 'file write('\ 'for cmd in self graphicscommandsfile write('+str(cmd)+"\ " file write('\ ' file close( def savefile()filename tkinter... |
14,440 | python programming widthentry pack(widthsize set(str( ) radiuslabel tkinter label(sidebar,text="radius"radiuslabel pack(radiussize tkinter stringvar(radiusentry tkinter entry(sidebar,textvariable=radiussizeradiussize set(str( )radiusentry pack( button widget calls an event handler when it is pressed the circlehandler f... |
14,441 | def beginfillhandler()cmd beginfillcommand(fillcolor get()cmd draw(theturtleself graphicscommands append(cmd beginfillbutton tkinter button(sidebartext "begin fill"command=beginfillhandlerbeginfillbutton pack(fill=tkinter both def endfillhandler()cmd endfillcommand(cmd draw(theturtleself graphicscommands append(cmd end... |
14,442 | python programming theturtle pendown(for cmd in self graphicscommandscmd draw(theturtlescreen update(screen listen( screen onkeypress(undohandler" "screen listen( the main function in our gui program is very simple it creates the root window then it creates the drawingapplication frame which creates all the widgets and... |
14,443 | most xml elements are delimited by opening tag and closing tag the tag above is an opening tag its matching closing tag looks like this the slash just before the tag name means that it is closing tag an opening and closing tag may have text or other xml elements in between the two tags so xml documents may contain xml ... |
14,444 | python programming goto goto goto endfill xml files are text files they just contain extra xml formatted data to help standardize how xml files are read writing an xml file is as simple as writing text file while indentation is not necessary in xml filesit is often used to highlight the format of the file in sect the g... |
14,445 | writing graphics commands to an xml file file open(filename" "file write('\ 'file write('\ 'for cmd in self graphicscommandsfile write('+str(cmd)+"\ " file write('\ 'file close(writing an xml file is like writing any text file except that the text file must conform to the xml grammar specification there are certainly w... |
14,446 | python programming the xml document contains the graphicscommands element calling getelementsbytagname on graphicscommands returns list of all elements that match this tag name since we know there is only one of these tags in the filewe can write [ to get the first element from the list thenthe graphicscommands element... |
14,447 | summary in this first we have covered large amount of material which should be mostly review but probably covered some things that are new to you as well don' be too overwhelmed by it all the purpose of this is to get you asking questions about the things you don' understand if you don' understand somethingyou should a... |
14,448 | python programming review questions answer these short answermultiple choiceand true/false questions to test your mastery of the what does ide stand for and why is it good idea to use an ide what code would you write to create string containing the words happy birthday!write some code to point reference called text at ... |
14,449 | when traversing an xml documenthow do you get list of elements from itwhat line(sof code do you have to writeprovide an example what is an attribute in an xml document and how do you access an attribute' valueprovide an example from the text or from another example you find online programming problems starting with the... |
14,450 | python programming each stripe should have different color to vary the coloryou might convert -bit number to hex to convert number to hexadecimal in python you can use the hex function you must make sure that your color string is digits long and starts with pound sign ( #for it to be valid color string in python this c... |
14,451 | computational complexity in the last we developed drawing program to hold the drawing commands we built the pylist container class which is lot like the built-in python list classbut helps illustrate our first data structure when we added drawing command to the sequence we called the append method it turns out that thi... |
14,452 | computational complexity what is the definition of theta notationwhat is amortized complexity and what is its importancehow can we apply what we learned to make the pylist container class better computer architecture computer consists of central processing unit ( the cputhat interacts with input/output ( /odevices like... |
14,453 | fig conceptual view of computer ram into the cputhe operation is performedand the result is then typically written back into the ram the ram of computer is accessed frequently as program runsso it is important that we understand what happens when it is accessed (fig one analogy that is often used is that of post office... |
14,454 | computational complexity accessing elements in python list with experimentation we can verify that all locations within the ram of computer can be accessed in the same amount of time python list is collection of contiguous memory locations the word contiguous means that the memory locations of list are grouped together... |
14,455 | creates list of size with all ' lst [ let any garbage collection/memory allocation complete or at least settle down time sleep( time before the test retrievals starttime datetime datetime now( for in range( )find random location within the list and retrieve value do dummy operation with that value to ensure it is reall... |
14,456 | computational complexity when running program like this the times that you get will depend not only on the actual operations being performedbut the times will also depend on what other activity is occurring on the computer where the test is being run all modern operating systemslike mac os xlinuxor microsoft windowsare... |
14,457 | since we'll be taking look at quite bit of experimental data in this textwe have written tkinter program that will read an xml file with the format given in sect and plot the sequences to the screen the plotdata py program is given in chap if we use the program to plot the data gathered by the list access experimentwe ... |
14,458 | computational complexity multi-tasking system another factor is likely the caching of memory locations cache is way of speeding up access to memory in some situations and it is likely that the really low access times benefited from the existence of cache for the ram of the computer the experimental data backs up the cl... |
14,459 | in english this reads as followsthe class of functions designated by og( )consists of all functions fwhere there exists greater than and an ( positive integersuch that is less than or equal to (nis less than or equal to times (nfor all greater than or equal to if is an element of og( ))we say that (nis og( )the functio... |
14,460 | computational complexity because the time to access an element does not depend on nwe can pick ( sowe say that the average time to access an element in list of size is ( if we assume it never takes longer than us to access an element of list in pythonthen good choice for would be according to the definition above then ... |
14,461 | inefficient append class pylistdef __init__(self)self items [ the append method is used to add commands to the sequence def append(self,item)self items self items [item the code in sect appends new item to the list as follows the item is made into list by putting [andaround it we should be careful about how we say this... |
14,462 | computational complexity copy operations the third append requires three copy operations sowe have the following number of list elements being copied ** = in mathematics we can express this sum with summation symbol ( this is the mathematical way of expressing the sum of the first integers butwhat is this equal toit tu... |
14,463 | now we can use this fact in proving the equality of our original formula here we gon ii= - ( ( ( + + = if you look at the left side and all the way over at the right side of this formula you can see the two things that we set out to prove were equal are indeed equal this concludes our proof by induction the meta-proof ... |
14,464 | computational complexity on it the computer did nothing but sort those file names alphabetically for around when this was discoveredthe programmer rewrote the sorting code to be more efficient and reduced the sorting time to around that' big differenceit also illustrates just how important this idea of computational co... |
14,465 | in the pylist we go from to add another element to maybe secondbut probably less than that that' nice speedup in our program after making this changethe pylist append method is given in sect efficient append class pylistdef __init__(self)self items [ the append method is used to add commands to the sequence def append(... |
14,466 | computational complexity fig common big-oh complexities as possible as each of these techniques are exploredyou'll also have the opportunity to write some fun programs and you'll learn good deal about object-oriented programming more asymptotic notation earlier in this we developed big-oh notation for describing an upp... |
14,467 | the amount of time an algorithm takes to run andrelated to thatthe amount of space an algorithm uses while running typicallycomputer scientists will talk about space/time tradeoff in algorithms sometimes we can achieve faster running time by using more memory butif we use too much memory we can slow down the computer a... |
14,468 | computational complexity asymptotic lower bound ( ( ) (nc and omega notation serves as way to describe lower bound of function in this case the lower bound definition says for while it might be greaterbut eventually there is some where (ndominates (nfor all bigger values of in that casewe can write that the algorithm i... |
14,469 | fig lower and upper bound consider the pylist append operation discussed earlier in this the latest version of the pylist append method simply calls the python append operation on lists python is implemented in it turns out that while python supports an append operation for listslists are implemented as arrays in and i... |
14,470 | computational complexity pylist class class pylistthe size below is an initial number of locations for the list object the numitems instance variable keeps track of how many elements are currently stored in the list since self items may have empty locations at the end def __init__(self,size= )self items [nonesize self ... |
14,471 | consider sequence of append operations on an initially empty list appending the first element to the list is done in ( time since there is space for the first item added to the list because one slot was initially allocated in the list storing value in an already allocated slot takes ( time howeveraccording to the accou... |
14,472 | computational complexity the first time we need to double the size is when the second append is called there are two cyber dollars stored up at this point in time one of them is needed when copying the one element stored in the old list to the new fixed size list capable of holding two elements transition one in fig sh... |
14,473 | summary know how to use the datetime module to get information about the time it takes to complete an operation in program know how to write an xml file that can be used by the plotting program to plot information about the performance of an algorithm or piece of code understand the definition of big-oh notation and ho... |
14,474 | computational complexity programming problems devise an experiment to discover the complexity of comparing strings in python does the size of the string affect the efficiency of the string comparison and if sowhat is the complexity of the comparisonin this experiment you might want to consider best caseworst caseand av... |
14,475 | programming problems clearable listthen writing cl[itemwill return the item if it is in the list and return none otherwise writing cl[itemresults in method call of cl __getitem__(itemunlike the append operation described in sect when the clearable object fills up the list is automatically cleared or emptied on the next... |
14,476 | recursion don' think too hardthat' one of the central themes of this it' not often that you tell computer programmers not to think too hardbut this is one time when it is appropriate you need to read this if you have not written recursive functions before most computer science students start by learning to program in s... |
14,477 | recursion fig the python interpreter recursion is the way we will repeat code in this recursive function has no need for for or while loop goals by the end of this you should be able to answer these questions how does python determine the meaning of an identifier in programwhat happens to the run-time stack when functi... |
14,478 | scope to form complete mental picture of how your programs work we should further explore just how the python interpreter executes python program in the first we explored how references are the things which we name and that references point to objectswhich are unnamed howeverwe sometimes call an object by the name of t... |
14,479 | recursion fig scopes within simple program enclosing scope if python does not find the reference id within the local scopeit will examine the enclosing scope to see if it can find id there in the program in fig while python is executing the statement on line the enclosing scope is the purple region of the program the i... |
14,480 | conditions as defined in sect for the local scope the identifier must be defined using id it must be parameter to the enclosing functionor it must be an identifier for class or function definition in the enclosing scope' function on line when python encounters the identifier historyofoutput it finds that identifier def... |
14,481 | recursion built-in scope the final scope in python is the built-in scope if an identifier is not found within any of the nested scopes within module and it is not defined in the global scopethen python will examine the built-in identifiers to see if it is defined there for instanceconsider the identifier int if you wer... |
14,482 | record onto the run-time stack when function is called when function returns the python interpreter pops the corresponding activation record off the run-time stack python stores the identifiers defined in the local scope in an activation record when function is calleda new scope becomes the local scope at the same time... |
14,483 | recursion fig the run-time stack and the heap one important note should be made here figure shows historyofoutput as local variable in the showoutput function this is not really the casebecause the historyofoutput reference is not defined within the local scope of the showoutput function howeverdue to the way python is... |
14,484 | fig the wing ide showing the run-time stack writing recursive function recursive function is simply function that calls itself it' really very simple to write recursive functionbut of course you want to write recursive functions that actually do something interesting in additionif function just kept calling itself it w... |
14,485 | recursion eventually fill up the run-time stack and you will get stack overflow error when running such program to prevent recursive function from running foreveror overflowing the runtime stackevery recursive function must have base casejust like an inductive proof must have base case there are many similarities betwe... |
14,486 | int(input("please enter non-negative integer") sumfirstn( print("the sum of the first" "integers is"str( )+" if __name__ ="__main__"main(in this casethis would be the best function we could write because the complexity of the sumfirstn function is ( this means the time it takes to execute this function is not dependent... |
14,487 | recursion one thing that we might point out in this recursive function the else is not necessary when the python interpreter encounters return statementthe interpreter returns immediately and does not execute the rest of the function soin sect if the function returns in the then part of the if statementthe rest of the ... |
14,488 | fig the run-time stack of recursive function call each time the function is called new activation record is pushed and new copy of the local variables is stored within the activation record the picture in fig depicts the run-time stack at its deepest point when execution of the function gets to the point when equals th... |
14,489 | recursion fig the first return from recsumfirstn object containing on the heap is also reclaimed by the garbage collector because there are no references pointing at it anymore after the first return of the recsumfirstnthe python interpreter returns to line in the previous function call butthis statement contains retur... |
14,490 | fig the last return from recsumfirstn the program terminates after printing the to the screen and returning from the main function after line and from the module after line the importance of this example is to illustrate that each recursive call to recsumfirstn has its own copy of the variable because it is local to th... |
14,491 | recursion recursion in computer graphics recursion can be applied to lots of different problems including sortingsearchingdrawing picturesetc the program given in sect draws spiral on the screen as shown in fig recursive spiral import turtle def drawspiral(tlengthcolorcolorbase)#color is bit value that is changing bit ... |
14,492 | fig spiral image if __name__ ="__main__"main(in this program the drawspiral function is recursive it has base case that is written firstwhen the length of the side is zero it exits it calls itself on something smallerthe new length passed to it is the old length minus one the newcolor formula is perhaps the most comple... |
14,493 | recursion for in lstaccumulator [xaccumulator return accumulator def main()print(revlist([ , , , ]) if __name__ ="__main__"main(when runthis program prints [ to the screen the code in sect uses the accumulator pattern to solve the problem of reversing list this is pattern you have probably used before if you first lear... |
14,494 | reversing string def revstring( )if =""return " restrev revstring( [ :]first [ : now put the pieces together result restrev first return result def main()print(revstring("hello") if __name__ ="__main__"main(notice the similarity of these two functions the functions are nearly identical that' because the recursive defin... |
14,495 | recursion within list can serve to make the list or string smaller in that case it may be helpful to write function that calls helper function to do the recursion consider the program in sect this code uses nested helper function called revlisthelper to do the actual recursion the list itself does not get smaller in th... |
14,496 | using type reflection if seq =emptyseqreturn emptyseq restrev reverse(seq[ :]first seq[ : now put the pieces together result restrev first return result def main()print(reverse([ , , , ])print(reverse("hello")if __name__ ="__main__"main(after writing the code in sect we have polymorphic reverse function that will work ... |
14,497 | recursion review questions answer these short answermultiple choiceand true/false questions to test your mastery of the what is an interpreter what is the python interpreter called when the python interpreter sees an identifierin which scope does it look for the identifier first what order are the various scopes inspec... |
14,498 | programming problems fig tree write recursive function that takes string like "abcdefghand returns "badcfehgcall this function swap since it swaps every two elements of the original string put this function in program and call it with at least few test cases write recursive function that draws tree call your function d... |
14,499 | recursion the drawspiral function will be given radius for the sprial to get circular spiralevery recursive call to the drawspiral function must decrease the radius just bit and increase the angle you convert the angle and the radius to its ( ,ycoordinate equivalent and then draw line to that location you must also pas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.