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 such that ( < (nfor all theta notationth the notation th(nis the formal way to express both the lower bound and the upper bound of an algorithm' running time it is represented as followsth( ( ) (nif and only if (nn ( ( )and (no( ( )for all
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 text are intended as an introductory text for data structures and algorithmswhile the later cover advanced topics that are suitable for the second course in data structures and algorithms the python language is used throughout the text and some familiarity with python or some other object-oriented language is assumed howeverthe first contains python primer for those coming from different language background this text serves well as follow-on text to python programming fundamentals by kent lee and published by springerbut does not require you to have read that text in this text the next steps are taken to teach you how to handle large amounts of data efficiently number of algorithms are introduced and the need for them is motivated through examples that bring meaning to the problems we face as computer programmers an algorithm is well-defined procedure for accomplishing task algorithms are an important part of computer science and this text explores many algorithms to give you the background you need when writing programs of your own the goal is that having seen some of the sorts of algorithms presented in this textyou will be able to apply these techniques to other programs you write in the future another goal of this text is to introduce you to the idea of computational complexity while there are many unique and interesting algorithms that we could exploreit is important to understand that some algorithms are more efficient than others while computers are very good at doing calculations quicklyan inefficient algorithm can make the fastest computer seem very slow or even make it appear to come to halt this text will show you what can and cannot be computed efficiently the text builds this idea of efficiency from the most basic of facts giving you the tools you will need to determine just how efficient any algorithm is so you can make informed judgements about the programs you write this copy belongs to 'acha
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 text on data structures and algorithms whether you have used it before or not python is an object-oriented programming language with operator overloading and dynamic typing whether this is your first exposure to python or you used it in your first courseyou will learn more about the language from this text the first of the text reviews some of the fundamentals of computer programming along with the basic syntax of python to get you up to speed in the language then subsequent dive into more advanced topics and should be read in sequence at the beginning of every the goals of the are stated at the end of every is set of review questions that reinforce the goals of the these review questions are followed in each by few programming problems that relate to the goals by asking you to use the things you learned in the and apply them to computer program you can motivate your reading of by first consulting the review questions and then reading the to answer them along the waythere are lots of examples to illustrate the concepts being introduced we hope you enjoy the textif you have any questions or comments please send them to kentdlee@luther edu kent lee steve hubbard this copy belongs to 'acha
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 this text introduces complexity analysis and depending on your needssome of the material in chap could be skipped in an introductory data structures course in particularthe material on th notation and amortized complexity can be skipped big-oh notation is enough for the first seven typicallychap is covered lightly and near the end of semester course it seems there is generally not enough time in semester to cover graph theory in much detail advanced courses in data structures and algorithms should start with chap if students are unfamiliar with python or tkinter brief refresher may not be bad even for those that have programmed using python before should be covered in detail including the material on th notation and amortized complexity some review of hashing as it is used in sets and maps in chap may be good review earlier in the advanced course along with brief discussion of binary search trees and tree traversals in chap depending on your needschap would be good to cover next including the material on depth first search of graph is where the advanced material begins with assumptions made that students understand the concepts presented in the earlier the two introductory along with chaps - make seven-sequence that will fill semeseter in an advanced course nicely this text is very project oriented solutions for all projects are available from kent lee you can contact kent at kentdlee@luther edu for instructor solutions you must provide proof (through website or other referencethat you are an instructor at an educational institution to get access to the instructor materials vii this copy belongs to 'acha
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 registered trademark of microsoft corporation in the united stated and other countries ix this copy belongs to 'acha
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 files reading xml files summary review questions programming problems computational complexity goals computer architecture accessing elements in python list big-oh notation the pylist append operation proof by induction xi this copy belongs to 'acha
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 computer graphics recursion on lists and strings using type reflection summary review questions programming problems sequences goals lists cloning objects item ordering selection sort merge sort quicksort two-dimensional sequences the minimax algorithm linked lists stacks and queues summary review questions programming problems sets and maps goals playing sudoku sets hashing the hashset class solving sudoku this copy belongs to 'acha
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 notation searching graph kruskal' algorithm dijkstra' algorithm graph representations summary review questions programming problems membership structures goals bloom filters the trie datatype summary review questions programming problems heaps goals key ideas building heap the heapsort algorithm version analysis of version phase this copy belongs to 'acha
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 summary review questions programming problems -trees goals relational databases -tree organization the advantages of -trees -tree implementation -tree insert -tree delete summary review questions programming problems heuristic search goals depth first search breadth first search hill climbing best first search asearch minimax revisited summary review questions programming problems this copy belongs to 'acha
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 plotdata program the tic tac toe application the connect four front-end bibliography index this copy belongs to 'acha
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 fastest computers to grinding halt when working with large data sets this has happened beforeand soon you will understand just how easy it can occur but firstwe'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 computer the examples in this text use python python is not compatible with python so you'll want to be sure you have python or later installed on your computer when writing programs in any language good integrated development environment (ideis valuable tool so you'll want to install an idetoo examples within this text will use wing ide as pictured in fig although other acceptable ides are available as well the wing ide is well maintainedsimple to useand has nice debugger which will be useful as you write python programs if you want to get wing ide then go to ~leekent/cs has directions for installing both python and wing ide wing ide 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' 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 insectand it will ask you to save your program if you haven' 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 bit finallyyour python programs are interpreted by the python interpreter the shell is another name for the python interpreter and wing ide gives you access to shell within the ide (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha
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 found before your program runs these are things like missing colon or forgetting to indent something an ide like wing ide 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 run-time error you can look at the stack data tab as it appears in fig when 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' understand problemthe wing ide (and most other ideslets you step through your code so you can watch as an error is reproduced the three icons in the upper right corner of fig let you step into functionstep over codeand step out of functionrespectively stepping over or into your code can be valuable when trying to understand 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 breakpoint 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 this copy belongs to 'acha
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 for reading records from file you'll also see functions in python and begin to learn how to implement your own datatypes by designing and writing class definition goals by the end of this you should be able to answer these questions what two parts are needed for the accumulator patternwhen do you need to use the loop and half pattern for reading from filewhat is the purpose of class definitionwhat is an object and how do we create onewhat is mutator methodwhat is an accessor methodwhat is widget and how does one use widgets in gui programming creating objects python is an object-oriented language all data items in python are objects in pythondata items that could be thought of as similar are named by type or class the term type and class in python are synonymousthey are two names for the same thing so when you read about types in python you can think of classes or vice versa there are several built-in types of data in python including intfloatstrlistand dict which is short for dictionary these types of data and their associated operations are included in the appendices at the end of the text so you have quick reference if you need to refer to it while programming you can also get help for any type by typing help(typenamein the python shellwhere typename is type or class in python very good language reference can be found at official python documentation website literal values there are two ways to create objects in python in few casesyou can use literal value to create an object literal values are used when we want to set some variable to specific value within our program for examplethe literal denotes any object with the integer value of this creates an int object containing the value it also points the reference called at this object as pictured in fig all assignments in python point references this copy belongs to 'acha
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 this object other literal values may be written in python as well here are some literal values that are possible in python int literals - etc float literals - str literals'hi there'"how are youlist literals[][ 'hi there'dict literals{}{'hi there': 'how are you': python lets you specify float literals with an exponent so represents the float any number written with decimal point is floatwhether there is or some other value after the decimal point if you write number using the or exponent notationit is float as well any number without decimal point is an intunless it is written in 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 dictionary is mapping of keys to values in the dictionary literalthe key 'hi thereis mapped to the value and the key 'how are youis mapped to dictionaries will be covered in some detail in chap non-literal object creation most of the timewhen an object is createdit is not created from literal value of coursewe need literal values in programming languagesbut most of the time we have an object already and want to create another object by using one or more existing objects for instanceif we have string in pythonlike ' and want to create an int object from that stringwe can do the following ' int(yprint(xthis copy belongs to 'acha
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 any type or class name in pythonlike intfloatstr or any other type the other_object_values is comma-separated sequence of references to other objects that are needed by the class or type to create an instance ( an objectof that type here are some examples of creating objects from non-literal values float(' ' str(zu list(wthis results in the list [' ''' ' calling methods on objects 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 languagemutator and accessor methods accessor methods access the current state of an object but don' change the object accessor methods return new object references when called 'how are youy upper(print(yherethe method upper is called on the object that refers to the upper accessor method returns new objecta str objectthat is an upper-cased version of the original string note that 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 [ mylist reverse(print(mylistthis prints [ to the screen the reverse method mutates the existing objectin this case the list that mylist refers to once calleda mutator method can' be undone the change or mutation is permanent until mutated again by some other mutator method all classes contain accessor methods without accessor methodsthe class would be pretty uninteresting we use accessor methods to retrieve value that is stored in an object or to retrieve value that depends on the value stored in an object this copy belongs to 'acha
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 class does not have any mutator methods when class does not contain any mutator methodswe say that the class is immutable we can form new values from the data in an immutable classbut once an immutable object is createdit cannot be changed other immutable classes include int and float implementing class programming in an object-oriented language usually means implementing classes that describe objects which hold information that is needed by the program you are writing objects contain data and methods operate on that data class is the definition of the data and methods for specific type of object every class contains one special method called constructor the constructor' job is to create an instance of an object by placing references to data within the object itself for exampleconsider class called dog dog has namea birthdayand sound it makes when it barks when we create dog objectwe write code like that appearing in sect creating objects and calling methods boydog dog("mesa" "wooof"girldog dog("sequoia" "barkbark"print(boydog speak()print(girldog speak()print(boydog birthdate()print(girldog birthdate()boydog changebark("woofywoofy"print(boydog speak()once created in the memory of the computerdog objects looks like those appearing in fig each object is referenced by the variable reference assigned to iteither girldog or boydog in this case the objects themselves are collection of references that point to the information that is stored in the object each object has namemonthdayyearand speaktext references that point to the associated data that make up dog object to be able to create dog objects like these two objects we need dog class to define these objects in additionwe'll need to define speakbirthdateand changebark methods we can do this by writing class as shown in sect comments about each part of the class appear in the code the special variable self always points at the current object and must be the first parameter to each method in the class this copy belongs to 'acha
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 reference called "selfis created by python and made to point to the space for the newly created object python does this automatically for us but we have to have "selfas the first parameter to the __init__ method ( the constructordef __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 current object the current object appears on the left hand side of the dot ( the when the method is called def speak(self)return self speaktext here is an accessor method to get the name def getname(self)this copy belongs to 'acha
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 bark operator overloading python provides operator overloadingwhich is nice feature of programming languages because it makes it possible for the programmer to interact with objects in very natural way operator overloading is already implemented for variety of the built-in classes or types in python for instanceintegers ( the int typeunderstand how they can be added together to form new integer object addition is implemented by special method in python called the __add__ method when two integers are added togetherthis method is called to create new integer object if you look in the appendicesyou'll see examples of these special methods and how they are called for examplein chap the __add__ method is called by writing where is an integer the methods that begin and end with two underscores are methods that python associates with corresponding operator when we say that python supports operator overloading we mean that if you define method for your class with name that is operator overloadedyour class will support that operator as well python figures out which method to call based on the types of the operands involved for instancewriting calls the int class __add__ method when is an integerbut it calls the float type' __add__ method when is float this is because in the case of the __add__ methodthe object on the left hand side of the operator corresponds to the object on the left hand side of the dot ( the periodin the equivalent method call __add__(ythe object on the left side of the dot determines which add method is called the operator is overloaded if we wanted to define addition for our dog classwe would include an __add__ method in the class definition it might be natural to write boydog girldog to create new puppy object if we wished to do that we would extend our dog class as shown in sect the dog class with overloaded addition class dogthis is the constructor for the class it is called whenever dog object is created the reference called "selfis created by python and made to point to the space for the newly created object python does this automatically for us but we have to have "selfas the first parameter to the __init__ method ( the constructorthis copy belongs to 'acha
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 current object the current object appears on the left hand side of the dot ( the when the method is called def speak(self)return self speaktext here is an accessor method to get the name def getname(self)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 bark when creating the new puppy we don' know it' birthday pick the first dog' birthday plus one year the speaktext will be the concatenation of both dog' text the dog on the left side of the operator is the object referenced by the "selfparameter the "otherdogparameter is the dog on the right side of the operator def __add__(self,otherdog)return dog("puppy of self name and otherdog nameself monthself dayself year self speaktext otherdog speaktext def main()boydog dog("mesa" "woooof"girldog dog("sequoia" "barkbark"print(boydog speak()print(girldog speak()print(boydog birthdate()print(girldog birthdate()boydog changebark("woofywoofy"print(boydog speak()puppy boydog girldog print(puppy speak()print(puppy getname()print(puppy birthdate() if __name__ ="__main__"main(this text uses operator overloading fairly extensively there are many operators that are defined in python python programmers often call these operators magic methods because method automatically gets called when an operator is used in an expression many of the common operators are given in the table in fig for your this copy belongs to 'acha
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< % * ! - repr(x__setitem__(self, ,y__str__(selfx[iy str(x__sub__(self,yx- description the addition of two objects the type of determines which add operator is called when is collection you can test to see if is in it returns true or false depending on the values of and returns true or false depending on the values of and returns the item at the yth position in returns true or false depending on the values of and returns an integral value for returns an integer representation of returns an iterator object for the sequence returns true or false depending on the values of and returns the size of where has some length attribute returns true or false depending on the values of and returns the value of modulo this is the remainder of / returns the product of and returns true or false depending on the values of and returns the unary negation of returns string version of suitable to be evaluated by the eval function sets the item at the ith position in to return string representation of suitable for user-level interaction the difference of two objects fig python operator magic methods convenience for each operator the magic method is givenhow to call the operator is givenand short description of it as well in the tableself and refer to the same object the type of determines which operator method is called in each case in the table the repr(xand the str(xoperators deserve little more explanation both operators return string representation of the difference is that the str operator should return string that is suitable for human interaction while the repr operator is called when string representation is needed that can be evaluated for instanceif we wanted to define these two operators on the dog classthe repr method would return the string "dog('mesa' , , 'wooof')while the str operator might return just the dog' name the repr operatorwhen calledwill treat the string as an expression that could later be evaluated by the eval function in python whereas the str operator simply returns string for an object importing modules in pythonprograms can be broken up into modules typicallywhen you write program in python you are going to use code that someone else wrote code that others wrote is usually provided in module to use moduleyou import it there are two ways to import module for the drawing program we are developing in this we want to use turtle graphics turtle graphics was first developed long time ago for programming language called logo logo was created around so the basis for turtle graphics is pretty ancient in terms of computer science it still this copy belongs to 'acha
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 way you choose to import code may be personal preferencebut there are some implications about using the convenient method of importing code the convenient way to import the turtle module would be to write the following from turtle import turtle(this is convenientbecause whenever you want to use the turtle classyou can just write turtle which is convenientbut not completely safe because you then have to make sure you never use the identifier turtle for anything else in your code in factthere may be other identifiers that the turtle module defines that you are unaware of that would also be identifiers you should not use in your code the safe way to import the turtle module would be as follows import turtle turtle turtle(while this is not quite as convenientbecause you must precede turtle with "turtle "it is safe because the namespace of your module and the turtle module are kept separate all identifiers in the turtle module are in the turtle namespacewhile the local identifiers are in the local namespace this idea of namespaces is an important feature of most programming languages it helps programmers keep from stepping on each otherstoes the rest of this text will stick to using the safe method of importing modules indentation in python programs indentation plays an important role in python programs an indented line belongs to the line it is indented under the body of function is indented under its function definition line the then part of an if statement is indented under the if while loop' body is indented under it the methods of class are all indented under the class definition line all statements that are indented the same amount and grouped together are called block it is important that all statements within block are indented exactly the same amount if they are notthen python will complain about inconsistent indentation because indentation is so important to pythonthe wing ide lets you select series of lines and adjust their indentation as groupas shown in fig you first select the lines of the block and then press the tab key to increase their indentation to decrease the indentation of block you select the lines of the block and press shift-tab as you write python code this is common chore and being able to adjust the indentation of whole block at time is real timesaver this copy belongs to 'acha
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 first started the general outline of python program is given in sect python program structure imports at the top import turtle other function definitions followed by the main function definition def main()the main code of the program goes here turtle turtle( this code calls the main function to get everything started the condition in this if statement evaluates to true when the module is executed by the interpreterbut not when it is imported into another module if __name__ ="__main__"main(the if statement at the end of the code in sect is the first code executed after the import statements the if statement' condition evaluates to true when the this copy belongs to 'acha
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 main function later you will have the opportunity to write module to be imported into another module so it is good habit to form to always call the main function in this way reading from file to begin our drawing programlet' assume that picture is stored in file and we wish to read this file when the program is started we'll assume that each line of the file contains drawing command and its associated data we'll keep it simple and stick to drawing commands that look like this in the input filegotoxywidthcolor circleradiuswidthcolor beginfillcolor endfill penup pendown each line of the file will contain record with the needed information we can draw picture by providing file with the right sequence of these commands the file in sect contains records that describe pickup truck text file with single line records beginfillblack circle black endfill penup goto black pendown beginfillblack circle black endfill penup goto black pendown beginfillyellow goto- black goto- black goto black goto black goto black goto black goto black this copy belongs to 'acha
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 read the file by using for loop to read the lines of the file the code of sect is program that reads these commands and processes each record in the filedrawing the picture that it contains reading and processing single line records this imports the turtle graphics module import turtle the main function is where the main code of the program is written def main()this line reads line of input from the user filename input("please enter drawing filename" create turtle graphics window to draw in turtle turtle(the screen is used at the end of the program screen getscreen( the next line opens the file for "ror reading "wwould open it for writingand "awould open the file to append to it ( add to the endin this program we are only interested in reading the file file open(filename" " the following for loop reads the lines of the fileone at time and executes the body of the loop once for each line of the file for line in file the strip method strips off the newline character at the end of the line and any blanks that might be at the beginning or end of the line text line strip( the following line splits the text variable into its pieces for instanceif text contained "goto blackthen commandlist will be equal to ["goto"" "" "" ""black"after splitting text commandlist text split("," get the drawing command command commandlist[ if command ="goto"writing float(commandlist[ ]makes float object out of the string found in commandlist[ you can do similar conversion between types for int objects float(commandlist[ ] float(commandlist[ ]width float(commandlist[ ]color commandlist[ strip( width(widtht pencolor(colorthis copy belongs to 'acha
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" pendown(elseprint("unknown command found in file:",command #close the file file close( #hide the turtle that we used to draw the picture ht( this causes the program to hold the turtle graphics window open until the mouse is clicked screen exitonclick(print("program execution completed " this code calls the main function to get everything started if __name__ ="__main__"main(when you have data file where each line of the file is its own separate recordyou can process those records as we did in sect the general pattern is to open the fileuse for loop to iterate through the fileand have the body of the for loop process each record the pseudo-code in sect is the abstract pattern for reading one-line records from file pattern for reading single line records from file first the file must be opened file open(filename," " the body of the for loop is executed once for each line in the file for line in fileprocess each record of the file each record must be exactly one line of the input file what processing record means will be determined by the program you are writing print(line closing the file is always good ideabut it will be closed when your program this copy belongs to 'acha
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 able to check condition to see if you are done reading the file butto check the condition you must first try to read at least little of record this is kind of chicken and egg problem which came firstthe chicken or the eggcomputer programmers have name for this problem as it relates to reading from files it is called the loop and half pattern to use while loop to read from filewe need loop and half the half comes before the while loop consider the program we are writing in this let' assume that the records of the file cross multiple lines in factlet' assume that we have variable length records that isthe records of our file consist of one to five lines the drawing commands will be exactly as they were before butinstead of all the data for record appearing on one linewe'll put each piece of data on its own separate line as shown in sect text file with multiple line records beginfill black circle black endfill penup goto black pendown beginfill black circle black endfill penup goto this copy belongs to 'acha
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 in sect uses while loop to read these variable length records this copy belongs to 'acha
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 command file readline(strip( if the command is emptythen there are no more commands left in the file while command !"" now we must read the rest of the record and then process it because records are variable lengthwe'll use an if-elif to determine which type of record it is and then we'll read and process the record if command ="goto" float(file readline() float(file readline()width float(file readline()color file readline(strip( width(widtht pencolor(colort goto( ,yelif command ="circle"radius float(file readline()width float(file readline()color file readline(strip( width(widtht pencolor(colort circle(radiuselif command ="beginfill"color file readline(strip( fillcolor(colort begin_fill(elif command ="endfill" end_fill(elif command ="penup" penup(elif command ="pendown" pendown(elseprint("unknown command found in file:",command this is still inside the while loop we must (attempt toread the next command from the file if the read succeedsthen command will not be the empty string and the loop will be repeated if command is empty it is because there were no more commands in the file and the while loop will terminate command file readline(strip( this copy belongs to 'acha
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 must be tested prior to executing the loop reading line prior to the while loop is necessary so we can check to see if the file is empty or not the first line of every other record is read at the end of the while loop on line this is the loop and half pattern the first line of the first record is read before the while loop while the first line of every other record is read inside the while loop just before the end when the condition becomes falsethe while loop terminates the abstract pattern for reading multi-line records from file is shown in sect there are certainly other forms of this pattern that can be usedbut memorizing this pattern is worth-while since the pattern will work using pretty much any programming language pattern for reading multi-line records from file first the file must be opened file open(filename" " read the first line of the first record in the file of coursefirstline should be called something that makes sense in your program firstline file readline(strip( while firstline !""read the rest of the record secondline file readline(strip(thirdline file readline(strip( then process the record this will be determined by the program you are writing print(firstlinesecondlinethirdline finallyfinish the loop by reading the first line of the next record to set up for the next iteration of the loop firstline file readline(strip( it' good idea to close the filebut it will be automatically closed when your program terminates file close(this copy belongs to 'acha
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 want to do with this container class our program will begin by creating an empty container to do thiswe'll write line like this graphicscommands pylist(thenwe will want to add graphics commands to our list using an append method like this command gotocommand(xywidthcolorgraphicscommands append(commandwe would also like to be able to iterate over the commands in our list for command in graphicscommandsdraw each command on the screen using the turtle called command draw(tat this pointour container class looks lot like list we are defining our own list class to illustrate first data structure and to motivate discussion of how lists can be implemented efficiently in this and the next polymorphism one important concept in object-oriented programming is called polymorphism the word polymorphic literally means many forms as this concept is applied to computer programmingthe idea is that there can be many ways that particular behavior might be implemented in relationship to our pylist container class that we are buildingthe idea is that each type of graphics command will know how to draw itself correctly for instanceone type of graphics command is the gotocommand when gotocommand is drawn it draws line on the screen from the current point to some new ( ,ycoordinate butwhen circlecommand is drawnit draws circle on the screen with particular radius this polymorphic behavior can be defined by creating class and draw method for each different type of behavior the code in sect is collection of classes that define the polymorphic behavior of the different graphics draw methods there is one class for each drawing command that will be processed by the program this copy belongs to 'acha
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 when traversing sequence of these commands polymorphism occurs when the "rightdraw method gets called without having to know which graphics command it is being called on class gotocommandhere the constructor is defined with default values for width and color this means we can construct gotocommand objects as gotocommand( , )or gotocommand( , , )or gotocommand( , , ,"yellow"def __init__(self, , ,width= ,color="black")self self self color color self width width def draw(self,turtle)turtle width(self widthturtle pencolor(self colorturtle goto(self ,self class circlecommanddef __init__(self,radiuswidth= ,color="black")self radius radius self width width self color color def draw(self,turtle)turtle width(self widthturtle pencolor(self colorturtle circle(self radius class beginfillcommanddef __init__(self,color)self color color def draw(self,turtle)turtle fillcolor(self colorturtle begin_fill( class endfillcommanddef __init__(self)pass is statement placeholder and does nothing we have nothing to initialize in this class because all we want is the polymorphic behavior of the draw method pass def draw(self,turtle)turtle end_fill( class penupcommanddef __init__(self)pass def draw(self,turtle)turtle penup(this copy belongs to 'acha
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 seen patterns of programmingsometimes called idiomsare important in computer science once we have learned an idiom we can apply it over and over in our programs this is useful to us because as we solve problems its nice to say"ohyesi can solve this problem using that idiomhaving idioms at our fingertips frees our minds to deal with the tougher problems we encounter while programming one important pattern in programming is the accumulator pattern this pattern is used in nearly every program we write when using this pattern you initialize an accumulator before loop and then inside the loop you add to the accumulator for instancethe code in sect uses the accumulator pattern to construct the list of squares from to list of squares initialize the accumulatorin this case list accumulator [ write some kind of for loop or while loop for in range( , )add to the accumulatorin this case add to the list accumulator accumulator [ * to complete our graphics programwe'll use the loop and half pattern to read the records from file and the accumulator pattern to add command object to our pylist container for each record we find in the file the code is given in sect graphics program import turtle command classes would be inserted here but are left out because they were defined earlier in the this copy belongs to 'acha
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 we try to write for cmd in seqwhere seq is one of these sequences the yield below will yield an element of the sequence and will suspend the execution of the for loop in the method below until the next element is needed the ability to yield each element of the sequence as needed is called "lazyevaluation and is very powerful it means that we only need to provide access to as many of elements of the sequence as are necessary and no more def __iter__(self)for in self itemsyield def main()filename input("please enter drawing filename" turtle turtle(screen getscreen(file open(filename" " create pylist to hold the graphics commands that are read from the file graphicscommands pylist( command file readline(strip( while command !"" now we must read the rest of the record and then process it because records are variable lengthwe'll use an if-elif to determine which type of record it is and then we'll read and process the record in this programprocessing the record means creating command object using one of the classes above and then adding that object to our graphicscommands pylist object if command ="goto" float(file readline() float(file readline()width float(file readline()color file readline(strip(cmd gotocommand( , ,width,color elif command ="circle"radius float(file readline()width float(file readline()color file readline(strip(cmd circlecommand(radius,width,color elif command ="beginfill"color file readline(strip(this copy belongs to 'acha
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 exception is common exception to raise the string will be printed when the exception is printed raise runtimeerror("unknown commandcommand finish processing the record by adding the command to the sequence graphicscommands append(cmd read one more line to set up for the next time through the loop command file readline(strip( this code iterates through the commands to do the drawing and demonstrates the use of the __iter(self)__ method in the pylist class above for cmd in graphicscommandscmd draw( file close( ht(screen exitonclick(print("program execution completed " if __name__ ="__main__"main( implementing gui with tkinter the word gui means graphical user interface implementing graphical user interface in python is very easy using module called tkinter the tcl/tk language and toolkit was designed as cross-platform method of creating gui interfaces python provides an interface to this toolkit via the tkinter module gui is an event-driven program this means that you write your code to respond to events that occur in the program the events occur as result of mouse clicksdragging the mousebutton pressesand menu items being selected to build gui you place widgets in window widgets are any element of gui like labelsbuttonsentry boxesand sometimes invisible widgets called frames frame is widget that can hold other widgets the drawing application you see in fig is one such gui built with tkinter in this section we'll develop this drawing application so you learn how to create your own gui applications using tkinter and to improve or refresh your python programming skills this copy belongs to 'acha
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 drew for usthanks denise!we also need to create event handlers to handle events in the drawing application putting widgets in window is called layout laying out window relies on layout manager of some sort windowing toolkits support some kind of layout in tkinter you either packgridor place widgets within window when you pack widgets it' like packing suitcase and each widget is stacked either beside or below the previous widget packed in the gui packing widgets will give you the desired layout in most situationsbut at times grid may be useful for laying out window the place layout manager lets you place widgets at particular location within window we'll use the pack layout manager to layout our drawing application when packing widgetsto get the proper layoutsometimes you need to create frame widget frame widgets hold other widgets in fig two frame widgets have been created the drawingapplication frame is the size of the whole window and holds just two widgets that are placed side by side within itthe canvas and the sidebar frame canvas is widget on which turtle can draw the sidebar widget holds all the buttonsentry boxesand labels this copy belongs to 'acha
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 objectsthe frame part of the drawingapplication and the rest of itwhich in this case is the pylist sequence of graphics commands our frame will keep track of the graphics commands that are used to draw the picture on the canvas portions of the code appear in sect the code in sect shows you all the widgets that are created and how they are packed within the window the canvas and the sidebar widgets are added side by side to the drawing application frame then all the entrylabeland button widgets are added to the sidebar frame in additionthere is menu with the draw application the menu is another widget that is added to the window (called self master in the code in sect the filemenu is what appears on the menu bar the menu items "new""load ""load into ""save as "and "exitare all added to this menu each menu item is linked to an event handler that is executed when it is selected when theturtle object is created in sect it is created as rawturtle rawturtle is just like turtle except that rawturtle can be provided canvas to draw on turtle object creates its own canvas when the first turtle is created since we already have canvas for the turtlewe create rawturtle object this copy belongs to 'acha
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 application this class defines the drawing application the following line says that the drawingapplication class inherits from the frame class this means that drawingapplication is like frame object except for the code written here which redefines/extends the behavior of frame class drawingapplication(tkinter frame)def __init__(selfmaster=none)super(__init__(masterself pack(self buildwindow(self graphicscommands pylist( this method is called to create all the widgetsplace them in the guiand define the event handlers for the application def buildwindow(self) the master is the root window the title is set as below self master title("draw" here is how to create menu bar the tearoff= means that menus can' be separated from the window which is feature of tkinter bar tkinter menu(self masterfilemenu tkinter menu(bar,tearoff= this code is called by the "newmenu item below when it is selected the same applies for loadfileaddtofileand savefile below the "exitmenu item below calls quit on the "masteror root window def newwindow()this sets up the turtle to be ready for new picture to be drawn it also sets the sequence back to empty it is necessary for the graphicscommands sequence to be in the object ( self graphicscommandsbecause otherwise the statementgraphicscommands pylist(would make this variable local variable in the newwindow method if it were localit would not be set anymore once the newwindow method returned theturtle clear(theturtle penup(theturtle goto( , theturtle pendown(screen update(screen listen(self graphicscommands pylist( filemenu add_command(label="new",command=newwindow the parse function adds the contents of an xml file to the sequence def parse(filename)xmldoc xml dom minidom parse(filename graphicscommandselement xmldoc getelementsbytagname("graphicscommands")[ graphicscommands graphicscommandselement getelementsbytagname("command" for commandelement in graphicscommandsprint(type(commandelement)command commandelement firstchild data strip(attr commandelement attributes if command ="goto"this copy belongs to 'acha
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 ="beginfill"color attr["color"value strip(cmd beginfillcommand(color elif command ="endfill"cmd endfillcommand( elif command ="penup"cmd penupcommand( elif command ="pendown"cmd pendowncommand(elseraise runtimeerror("unknown commandcommand self graphicscommands append(cmd def loadfile() filename tkinter filedialog askopenfilename(title="select graphics file" newwindow( this re-initializes the sequence for the new picture self graphicscommands pylist( calling parse will read the graphics commands from the file parse(filename for cmd in self graphicscommandscmd draw(theturtle this line is necessary to update the window after the picture is drawn screen update( filemenu add_command(label="load ",command=loadfile def addtofile()filename tkinter filedialog askopenfilename(title="select graphics file" theturtle penup(theturtle goto( , theturtle pendown(theturtle pencolor("# "theturtle fillcolor("# "cmd penupcommand(self graphicscommands append(cmdcmd gotocommand( , , ,"# "self graphicscommands append(cmdcmd pendowncommand(self graphicscommands append(cmdscreen update(parse(filename for cmd in self graphicscommandscmd draw(theturtlethis copy belongs to 'acha
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 filedialog asksaveasfilename(title="save picture as "write(filename filemenu add_command(label="save as ",command=savefile filemenu add_command(label="exit",command=self master quit bar add_cascade(label="file",menu=filemenu this tells the root window to display the newly created menu bar self master config(menu=bar here several widgets are created the canvas is the drawing area on the left side of the window canvas tkinter canvas(self,width= ,height= canvas pack(side=tkinter left by creating rawturtlewe can have the turtle draw on this canvas otherwisea rawturtle and turtle are exactly the same theturtle turtle rawturtle(canvas this makes the shape of the turtle circle theturtle shape("circle"screen theturtle getscreen( this causes the application to not update the screen unless screen update(is called this is necessary for the ondrag event handler below without itthe program bombs after dragging the turtle around for while screen tracer( this is the area on the right side of the window where all the buttonslabelsand entry boxes are located the pad creates some empty space around the side the side puts the sidebar on the right side of the this frame the fill tells it to fill in all space available on the right side sidebar tkinter frame(self,padx= ,pady= sidebar pack(side=tkinter rightfill=tkinter both this is label widget packing it puts it at the top of the sidebar pointlabel tkinter label(sidebar,text="width"pointlabel pack( this entry widget allows the user to pick width for their lines with the widthsize variable below you can write widthsize get(to get the contents of the entry widget and widthsize set(valto set the value of the entry widget to val initially the widthsize is set to str( is needed because the entry widget must be given string widthsize tkinter stringvar(widthentry tkinter entry(sidebar,textvariable=widthsizethis copy belongs to 'acha
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 function below is the event handler when the draw circle button is pressed def circlehandler()when drawinga command is created and then the command is drawn by calling the draw method adding the command to the graphicscommands sequence means the application will remember the picture cmd circlecommand(float(radiussize get())float(widthsize get())pencolor get()cmd draw(theturtleself graphicscommands append(cmd these two lines are needed to update the screen and to put the focus back in the drawing canvas this is necessary because when pressing "uto undothe screen must have focus to receive the key press screen update(screen listen( this creates the button widget in the sidebar the fill=tkinter both causes the button to expand to fill the entire width of the sidebar circlebutton tkinter button(sidebartext "draw circle"command=circlehandlercirclebutton pack(fill=tkinter both the color mode below allows colors to be specified in rgb form ( redgreen/bluethe mode allows the red value to be set by two digit hexadecimal number ranging from -ff the same applies for blue and green values the color choosers below return string representing the selected color and slice is taken to extract the #rrggbb hexadecimal string that the color choosers return screen colormode( penlabel tkinter label(sidebar,text="pen color"penlabel pack(pencolor tkinter stringvar(penentry tkinter entry(sidebar,textvariable=pencolorpenentry pack(this is the color black pencolor set("# " def getpencolor()color tkinter colorchooser askcolor(if color !nonepencolor set(str(color)[- :- ] pencolorbutton tkinter button(sidebartext "pick pen color"command=getpencolorpencolorbutton pack(fill=tkinter both filllabel tkinter label(sidebar,text="fill color"filllabel pack(fillcolor tkinter stringvar(fillentry tkinter entry(sidebar,textvariable=fillcolorfillentry pack(fillcolor set("# " def getfillcolor()color tkinter colorchooser askcolor(if color !nonefillcolor set(str(color)[- :- ] fillcolorbutton tkinter button(sidebartext "pick fill color"command=getfillcolorfillcolorbutton pack(fill=tkinter both this copy belongs to 'acha
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 endfillbutton tkinter button(sidebartext "end fill"command=endfillhandlerendfillbutton pack(fill=tkinter both penlabel tkinter label(sidebar,text="pen is down"penlabel pack( def penuphandler()cmd penupcommand(cmd draw(theturtlepenlabel configure(text="pen is up"self graphicscommands append(cmd penupbutton tkinter button(sidebartext "pen up"command=penuphandlerpenupbutton pack(fill=tkinter both def pendownhandler()cmd pendowncommand(cmd draw(theturtlepenlabel configure(text="pen is down"self graphicscommands append(cmd pendownbutton tkinter button(sidebartext "pen down"command=pendownhandlerpendownbutton pack(fill=tkinter both here is another event handler this one handles mouse clicks on the screen def clickhandler( , )when mouse click occursget the widthsize entry value and set the width of the pen to the widthsize value the float(widthsize get()is needed because the width is floatbut the entry widget stores it as string cmd gotocommand( , ,float(widthsize get()),pencolor get()cmd draw(theturtleself graphicscommands append(cmdscreen update(screen listen( here is how we tie the clickhandler to mouse clicks screen onclick(clickhandler def draghandler( , )cmd gotocommand( , ,float(widthsize get()),pencolor get()cmd draw(theturtleself graphicscommands append(cmdscreen update(screen listen( theturtle ondrag(draghandler the undohandler undoes the last command by removing it from the sequence and then redrawing the entire picture def undohandler()if len(self graphicscommands self graphicscommands removelast(theturtle clear(theturtle penup(theturtle goto( , this copy belongs to 'acha
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 has the logic for the event handlers calling mainloop on the frames makes it start listening for events the mainloop function will return when the application is exited def main()root tkinter tk(drawingapp drawingapplication(root drawingapp mainloop(print("program execution completed " if __name__ ="__main__"main( xml files reading standard text filelike the graphics commands file we read using the loop and half pattern in sect is common task in computer programs the only problem is that the program must be written to read the specific format of the input file if we later wish to change the format of the input file to includefor examplea new option like fill color for circlethen we are stuck updating the program and updating all the files it once read the input file format and the program must always be synchronized this means that all old formatted input files must be converted to the new format or they must be thrown away that is simply not acceptable to most businesses because data is valuable to deal with this problemcomputer programmers designed language for describing data input files called xml which stands for extensible markup language xml is meta-language for data description meta-language is language for describing other languages the xml meta-language is universally accepted in factthe xml format is governed by standards committeewhich means that we can count on the xml format remaining very stable and backwards compatible forever any additions to xml will have to be compatible with what has already been defined an xml document begins with special line to identify it as an xml file this line looks like this the rest of an xml file consists of elements or nodes each node is identified by tag or pair of beginning and ending tags each tag is delimited ( surroundedby angle brackets for instancehere is one such tag this copy belongs to 'acha
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 elements nested as deeply as necessary depending on the data you are trying to encode each xml element may have attributes associated with it for instanceconsider an xml element that encapsulates the information needed to do goto graphics command to complete goto command we need the and coordinatesthe width of the lineand the pen color here is an example of encoding that information in xml format goto in this example the attributes are xywidthand color each attribute is mapped to its value as shown above the goto text is the text that appears between the opening and closing tags that text is sometimes called the child data by encoding an entire graphics commands input file in xml format we eliminate some of the dependence between the draw program and its data except for the xml format ( the grammarthe contents of the xml file are completely up to the programmer or programmers using the data the file in sect is an example of the truck picture' xml input file the truck xml file beginfill circle endfill penup goto pendown beginfill circle endfill penup goto pendown beginfill goto goto goto goto goto this copy belongs to 'acha
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 graphicscommands element contains one command element for each drawing command in the picture each drawing command contains the command type as its text the command types are gotocirclebeginfillendfillpenupand pendown the attributes of command are data like xywidthradiusand color that are used by the various types of commands to write the commands to fileeach of the command classes can be modified to produce an xml element when converted to string using the special __str__ method for instancesect contains the modified gotocommand class supporting the creation of an xml element the gotocommand with xml creation code the following classes define the different commands that are supported by the drawing application class gotocommanddef __init__(self, , ,width= ,color="black")self self self width width self color color the draw method for each command draws the command using the given turtle def draw(self,turtle)turtle width(self widthturtle pencolor(self colorturtle goto(self ,self the __str__ method is special method that is called when command is converted to string the string version of the command is how it appears in the graphics file format def __str__(self)return '<command ="str(self ' ="str(self 'width="str(self width'color="self color '">gotoby returning string like this from each of the command objectsthe code to write the draw program' data to file is very simple all that is needed is some code that writes the xml line as the first linefollowed by the tag and the command elements finallythe tag must be written the code in sect accomplishes this this copy belongs to 'acha
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 ways to create xml files that differ from how it was presented in sect in the next section we'll learn about xml parsers and very simple way to read xml documents it turns out there are at least some xml frameworks that make writing an xml document just as simple reading xml files xml files would be difficult to read if we had to read them like we read regular text file this is especially true because xml files are not line-oriented they conform to the xml grammarbut the grammar does not specify anything about the lines in the file instead of reading an xml file by reading lines of the filewe use special tool called parser parser is written according to the rules of grammarin this case the xml grammar there are many xml parsers that have been written and different parsers have different features the one we will use in this text is one of the simpler parsers called minidom the minidom parser reads an entire xml file by calling the parse method on it it places the entire contents of an xml file into an sequence of element objects an element object contains the child data and attributes of an xml element along with any other elements that might be defined inside this element to use the minidom parseryou must first import the module where the minidom parser is defined import xml dom minidom thenyou can read an entire xml file by calling the parse method on an xml document as follows xmldoc xml dom minidom parse(filenameonce you have done thatyou can read specific type of element from the xml file by calling the method getelementsbytagname on it for instanceto get the graphicscommands element from the graphics commands xml fileyou would write this graphicscommands xmldoc getelementsbytagname("graphicscommands")[ this copy belongs to 'acha
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 contains just the one element from the file and all the command elements of the file are located within it if we want to go through all these elements we can use for loop as in the code in sect using an xml parser for commandelement in graphicscommandsprint(type(commandelement)command commandelement firstchild data strip(attr commandelement attributes if command ="goto" 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 ="beginfill"color attr["color"value strip(cmd beginfillcommand(color elif command ="endfill"cmd endfillcommand( elif command ="penup"cmd penupcommand( elif command ="pendown"cmd pendowncommand(elseraise runtimeerror("unknown commandcommand self append(cmdin the code in sect the attr variable is dictionary mapping the attribute names ( keysto their associated values the child data of command node can be found by looking at the firstchild data for the node the strip method is used to strip away any unwanted blankstabsor newline characters that might appear in the string this copy belongs to 'acha
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 ask your teacher or someone who knows more about programming in python they can likely help you asking questions is great way to learn and computer science is all about lifetime of learning here is list of the important concepts you should have learned in this you shouldknow how to create an objectboth from literal value and by calling the object' constructor explicitly understand the concept of reference pointing at value ( an objectin python know how to call method on an object know how to import module understand the importance of indentation in python programs know why you write main function in python programs and how to call the main function know how to read records from file whether they be multi-linesingle linefixed lengthor variable length records know how to define container class like pylist defined in this understand the concept of polymorphism and how that means an object will do the right thing when method is called understand the accumulator pattern and how to use it in program know how to implement simple gui using tkinter in python entry boxeslabelsbuttonsframesand event handlers should all be concepts that are understood and can be programmed by looking back at the examples in this and finally you should know how to read and write xml files in your programs there is lot of example code in this and the final version of the draw program is provided on the text' website or in sect while it is doubtful you will be able to memorize each line of the code you found in this you should make sure you know how things work when you look at it and you should remember that you can use this as resource come back to it often when you need to see how to do something in later using this example code as reference will help to answer lot of your questions in future this copy belongs to 'acha
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 that newly created object what code would you write to take the string you created in the last question and split it into list containing two stringspoint the reference lst at this newly created list what code would you write to upper-case the string created in the second question point the reference named bdaywish at this upper-cased string if you were to execute the code you wrote for answering the last three questionswhat would the string referenced by text contain after executing these three lines of code how would you create dictionary that maps "kentto "deniseand maps "steveto "lindy"in these two cases "kentand "steveare the keys and "deniseand "lindyare the values consult chap how would you map key to value as in the previous problem when the dictionary was first created as an empty dictionaryhintthis would be called setting an item in the documentation in the appendix write short piece of code to create an empty dictionary and then map "kentto "deniseand "steveto "lindy what method is called when is writtenin which class is the method memberin other wordsif you were presented with in programhow would you figure out which class you needed to examine to understand exactly what meant what method is called when is written what is the loop and half problem and how is it solved do you need to use the solution to the loop and half problem to read an xml filewhy or why not polymorphism and operator overloading are closely related concepts can you briefly explain how the two concepts are similar and how python supports themhintno is not valid answer what would you write so that program asks the user to enter an integer and then adds up all the even integers from to the integer entered by the user hintyou might want to review how to use the range function to accomplish this and decide on what pattern of programming you might use how do you create window using tkinter what is the purpose of frame object in tkinter program what are three types of widgets in the tkinter framework when reading an xml filehow many lines of code does it take to read the file how do you get single element from an xml documentwhat line(sof code do you have to writeprovide an example this copy belongs to 'acha
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 version of the draw program that reads an input file with variable length recordsadd new graphics command of your choice to the program consider how it would be written to filecreate test filewrite your codeand test it you must design two filesa sample test fileand the program itself some examples might be graphics command to draw star with some number of pointsa rectangle with height and widthetc starting with the draw program provided in sect extend the program to include new button to draw new shape for the draw program for instancehave the draw program draw star on the screen or smiley face or something of your choosing hintif you use the forward and back methods to draw your shapeyou can scale it by multiplying each forward and back amount by scale value thenyou can let the user pick scale for it (or use the radius amount as your scaleand draw your shape in whatever size you like to complete this exercise you must extend your xml format to include new graphics command to store the relevant information for drawing your new shape you must also define new graphicscommand class for your new shape add the ability to draw text string on draw picture you'll need to let the user pick point size for real challengelet the user pick the font type from drop-down list of font types draw string that you have the user enter in an entry box find an xml document of your choice on the internetwrite code to parse through the data and plot something from that data whether it be some value over time or something else use turtle graphics to plot the data that you find add new button to the drawing program presented in sect that draws rainbow centered above the current location of the turtle this can be done quite easily by using sin and cos ( sine and cosinethe sin and cos functions take radians as parameter to draw rainbowthe radians would range from to math pi from the math module you must import the math module to get access to math cos and math sin as well as math pi to draw values in an arcyou can use for loop and let variableirange from to then radius math cos( / math pi)radius math sin( / math piis the next , coordinate of the rainbow' arc by varying the radius you will get several stripes for your rainbow this copy belongs to 'acha
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 copy belongs to 'acha
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 this method is called lot in factthe flower picture in the first took around commands to draw you can imagine that complex picture with lots of free-hand drawing could contain thousands of drawing commands when creating free-hand drawing we want to append the next drawing command to the sequence quickly because there are so many commands being appended how long does it take to append drawing command to the sequencecan we make guessshould we care about the exact amount of timein this you'll learn how to answer these questions and you'll learn what questions are important for you as computer programmer first you'll read about some principles of computer architecture to understand something about how long it takes computer to do some simple operations with that knowledge you'll have the tools you'll need to make informed decisions about how much time it might take to execute some code you have written goals by the end of this you should be able to answer these questions what are some of the primitive operations that computer can performhow much time does it take to perform these primitive operationswhat does the term computational complexity meanwhy do we care about computational complexitywhen do we need to be concerned about the complexity of piece of codewhat can we do to improve the efficiency of piece of codewhat is the definition of big-oh notation(cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha
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 keyboardmousedisplayand network interface when you run program it is first read from storage device like hard drive into the random access memoryor ramof the computer ram loses its contents when the power is shut offso copies of programs are only stored in ram while they are running the permanent copy of program is stored on the hard drive or some other permanent storage device the ram of computer holds program as it is executing and also holds data that the program is manipulating while program is runningthe cpu reads input from the input devices and stores data values in the ram the cpu also contains very limited amount of memoryusually called registers when an operation is performed by the cpusuch as adding two numbers togetherthe operands must be in registers in the cpu typical operations that are performed by the cpu are additionsubtractionmultiplicationdivisionand storing and retrieving values from the ram running program when user runs program on computerthe following actions occur the program is read from the disk or other storage device into ram the operating system (typically mac os xmicrosoft windowsor linuxsets up two more areas of ram called the run-time stack and the heap for use by the program the operating system starts the program executing by telling the cpu to start executing the first instruction of the computer the program reads data from the keyboardmousediskand other input sources each instruction of the program retrieves small pieces of data from ramacts on themand writes new data back to ram once the data is processed the result is provided as output on the screen or some other output device because there is so little memory in the cputhe normal mode of operation is to store values in the ram until they are needed for cpu operation the ram is much bigger storage space than the cpu butbecause it is biggerit is also slower than the cpu storing value in ram or retrieving value from ram can take as much time as several cpu operations when neededthe values are copied from the this copy belongs to 'acha
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 the ram of computer is like collection of post office boxes each box has an address and can hold value the values you can put in ram are called bytes ( eight bits grouped togetherwith eight bits different values can be stored usually bytes are interpreted as integersso byte can hold values from to if we want to store bigger valueswe can group bytes together into words the word size of computer is either bits ( four bytesor bitsdepending on the architecture of the computer' hardware all modern computer hardware is capable of retrieving or storing word at time the post office box analogy helps us to visualize how the ram of computer is organizedbut the analogy does not serve well to show us how the ram of computer behaves if we were going to get something from post office boxor store something in post office boxthere would have to be some kind of search done to find the post office box first then the letter or letters could be placed in it or taken from it the more post office boxes in the post officethe longer that search would take this helps us understand the fundamental problem we study in this text as the size of problem space growshow does program or algorithm behavein terms of this analogyas the number of post office boxes growshow much longer does it take to store or retrieve valuethe ram of computer does not behave like post office the computer does not need to find the right ram location before the it can retrieve or store value much better analogy is group of peopleeach person representing memory location within the ram of the computer each person is assigned an address or name to store value in locationyou call out the name of the person and then tell them what value to remember it does not take any time to find the right person because all the people are listeningjust in case their name is called to retrieve valueyou call the name of the person and they tell you the value they were told to remember in this way it takes exactly the same amount of time to retrieve any value from any memory location this is how the ram of computer works it takes exactly the same amount of time to store value in any location within the ram likewiseretrieving value takes the same amount of time whether it is in the first ram location or the last this copy belongs to 'acha
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 consecutively in ram if we want to verify that the ram of computer behaves like group of people all remembering their names and their valueswe can run some tests with python lists of different sizes to find the average time to retrieve from or store value into random element of the list to test the behavior of python lists we can write program that randomly stores and retrieves values in list we can test two different theories in this program the size of list does not affect the average access time in the list the average access time at any location within list is the sameregardless of its location within the list to test these two theorieswe'll need to time retrieval and storing of values within list thankfullypython includes datetime module that can be used to record the current time by subtracting two datetime objects we can compute the number of microseconds ( millionths of secondfor any operation within program the program in sect was written to test list access and record the access time for retrieving values and storing values in python list list access timing import datetime import random import time def main() write an xml file with the results file open("listaccesstiming xml"," " file write('\ ' file write('\ ' test lists of size to xmin xmax record the list sizes in xlist and the average access time within list that size in ylist for retrievals xlist [ylist [ for in range(xminxmax+ ) xlist append( prod this copy belongs to 'acha
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 really retrieved index random randint( , - val lst[indexprod prod val time after the test retrievals endtime datetime datetime now( the difference in time between start and end deltat endtime starttime divide by for the average access time but also multiply by for microseconds accesstime deltat total_seconds( ylist append(accesstime file write(file write(file write(file write(\ 'list size\ 'microseconds\ '\ 'file write(\ ' for in range(len(xlist))file write(\ ' file write(\ ' this part of the program tests access at random locations within list of , elements to see that all the locations can be accessed in about the same amount of time xlist lst ylist [ time sleep( for in range( )starttime datetime datetime now(index random randint( , - xlist[indexxlist[index endtime datetime datetime now(deltat endtime starttime ylist[indexylist[indexdeltat total_seconds( file write(\ ' for in range(len(xlist))if xlist[ file write(\ ' file write(\ 'file write('\ 'file close(if __name__ ="__main__"main(this copy belongs to 'acha
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 multi-tasking this means the operating system can switch between tasks so that we can get email while writing computer programfor instance when we time something we will not only see the effects of our own program runningbut all programs that are currently running on the computer it is nearly impossible to completely isolate one program in multi-tasking system howevermost of the time short program will run without too much interruption the program in sect writes an xml file with its results the xml file format supports the description of experimentally collected data for two dimensional plot of one or more sequences of data one sample of the data that this program generates looks like sect the data is abbreviatedbut the format is as shown in sect plot xml sample list size microseconds this copy belongs to 'acha
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 see graph like the one in fig this graph provides the experimental data to back up the two statements we made earlier about lists in python the red line shows the average element access time of , element accesses on list of the given size the average access time (computed from sample of , random list accessesis no longer on list of , than it is on list of , while the exact values are not printed in the graphthe exact values are not important what we would be interested in seeing is any trend toward longer or shorter average access times clearly the only trend is that the size of the list does not affect the average access time there are some ups and downs in the experimental databut this is caused by the system being fig access times in python list this copy belongs to 'acha
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 claim that the size of list does not affect the average access time in the list the blue line in the plot is the result of doing list retrieval and store operations on one list of , elements the reason the blue line is higher than the red line is likely the result of doing both retrieval from and store operation into the element of the list in additionthe further apart the values in memorythe less likely cache will help reduce the access time whatever the reason for the blue line being higher the important thing to notice is that accessing the element at index takes no more time than accessing any other element of the sequence all locations within the list are treated equally this backs up the claim that the average access time at any location within list is the sameregardless of its location within the list big-oh notation whichever line we look at in the experimental datathe access time never exceeds us for any of the memory accesseseven with the other things the computer might be doing we are safe concluding that accessing memory takes less than us in fact us is much more time than is needed to access or store value in memory location our experimental data backs up the two claims we made earlier howevertechnicallyit does not prove our claim that accessing memory takes constant amount of time the architecture of the ram in computer could be examined to prove that accessing any memory location takes constant amount of time accessing memory is just like calling out name in group of people and having that person respond with the value they were assigned it doesn' matter which person' name is called out the response time will be the sameor nearly the same the actual time to access the ram of computer may vary little bit if cache is availablebut at least we can say that there is an upper bound to how much time accessing memory location will take this idea of an upper bound can be stated more formally the formal statement of an upper bound is called big-oh notation the big-oh refers to the greek letter omicron which is typically used when talking about upper bounds as computer programmersour number one concern is how our programs will perform when we have large amounts of data in terms of the memory of computerwe wanted to know how our program would perform if we have very large list of elements we found that all elements of list are accessed in the same amount of time independent of how big this list is let' represent the size of the list by variable called let the average access time for accessing an element of list of size be given by (nnow we can state the following ( ( ) this copy belongs to 'acha
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 function is called an asymptotic upper bound for in this case you may not be comfortable with the mathematical description above stated in english the set named og( )consists of the set of all functionsf( )that have an upper bound of dg( )as approaches infinity this is the meaning of the word asymptotic the idea of an asymptotic bound means that for some small values of the value of (nmight be bigger than the value of dg( )but once gets big enough ( bigger than )then for all bigger it will always be true that (nis less than dg(nthis idea of an asymptotic upper bound is pictured in fig for some smaller values the function' performanceshown in greenmay be worse than the blue upper bound linebut eventually the upper bound is bigger for all larger values of we have seen that the average time to access an element in list is constant and does not depend on the list size in the example in fig the list size is the in the definition and the average time to access an element in list of size is the (nfig an upper bound this copy belongs to 'acha
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 it must be the case that (nis less than or equal to once gets big enough the choice of ( is arbitrary in computing the complexity of accessing an element of list we could have chosen ( if ( were chosend might be chosen to be instead of butsince we are only concerned with the overall growth in the function gthe choice of or is irrelevant and the simplest function is chosenin this case ( in englishwhen an operation or program is ( )we say it is constant time operation or program this means the operation does not depend on the size of it turns out that most operations that computer can perform are ( for instanceadding two numbers together is ( operation so is multiplication of two numbers while both operations require several cycles in computerthe total number of cycles does not depend on the size of the integers or floating point numbers being added or multiplied cycle is simply unit of time in computer comparing two values is also constant time operation when computing complexityany arithmetic calculation or comparison can be considered constant time operation this idea of computational complexity is especially important when the complexity of piece of code depends on in the next section we'll see some code that depends on the size of the list it is working with and how important it is that we understand the implications of how we write even small piece of code the pylist append operation we have established that accessing memory location or storing value in memory location is ( )or constant timeoperation the same goes for accessing an element of list or storing value in list the size of the list does not change the time needed to access or store an element and there is fixed upper bound for the amount of time needed to access or store value in memory or in list with this knowledgelet' look at the drawing program again and specifically at the piece of code that appends graphics commands to the pylist this code is used lot in the program every time new graphics command is createdit is appended to the sequence when the user is doing some free-hand drawinghundreds of graphics commands are getting appended every minute or so since free-hand drawing is somewhat compute intensivewe want this code to be as efficient as possible this copy belongs to 'acha
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 the item itself is not changed new list is constructed from the item the two lists are concatenated together using the operator the operator is an accessor method that does not change either original list the concatenation creates new list from the elements in the two lists the assignment of self items to this new list updates the pylist object so it now refers to the new list the question we want to ask ishow does this append method perform as the size of the pylist growslet' consider the first time that the append method is called how many elements are in the list that is referenced by self itemszerorightand there is always one element in [itemso the append method must access one element of list to form the new listwhich also has one element in it what happens the second time the append method is calledthis timethere is one element in the list referenced by self items and again one element in [itemnowtwo elements must be accessed to form the new list the next time append is called three elements must be accessed to form the new list of coursethis pattern continues for each new element that is appended to the pylist when the nth element is appended to the sequence there will have to be elements copied to form the new list overallhow many elements must be accessed to append elements proof by induction we have already established that accessing each element of list takes constant amount of time soif we want to calculate the amount of time it takes to append elements to the pylist we would have to add up all the list accesses and multiply by the amount of time it takes to access list element plus the time it takes to store list element to count the total number of access and store operations we must start with the number of access and store operations for copying the list the first time an element is appended that' one element copied the second append requires two this copy belongs to 'acha
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 turns out with little workwe can find that the following is true ii= ( we can prove this is true using proof technique from mathematics called mathematical induction there are couple of variations of mathematical induction we'll use what is called weak induction to prove this when proving something using induction you are really constructing meta-proof meta-proof is set of steps that you can repeat over and over again to find your desired result the power of induction is that once we have constructed the meta-proofwe have proved that the result is true for all possible values of we want to prove that the formula given above is valid for all to do this we first show it is true for simple value of in our case we'll pick as our value of in that case we have the following = = ( this is surely true this step is called the base case of the inductive proof every proof by induction must have base case and it is usually trivial the next step is to create the meta-proof this meta-proof is called the inductive case when forming the inductive case we get to assume that the formula holds for all valuesmwhere is less than this is called strong induction in weak induction we get to assume that the formula is valid for - and we want to show that it is valid for we'll use weak induction in this problem to finish our proof againthis step helps us form set of steps that we can apply over and over again to get from our base case to whatever value of we need to find to begin we will make note of the following - + ii= = this is true by the definition of summation but now we have sum that goes to and weak induction says that we know the equation is valid for this is called the inductive hypothesis since it holds for we know the following is true we get this by substituting everyplace that we see an in the original formula - = ( ) this copy belongs to 'acha
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 is in the formula above it is template that we could use to prove that the equality holds for to prove the equality holds for we needed to use the fact that the equality holds for this was our base case once we have proved that it holds for we could use that same formula to prove that the equality holds for mathematical induction doesn' require us to go through all the steps as long as we've created this meta-proof we have proved that the equality holds for all that' the power of induction making the pylist append efficient nowgoing back to our original problemwe wanted to find out how much time it takes to append items to pylist it turns outusing the append method in sect it will perform in ( time this is because the first time we called append we had to copy one element of the list the second time we needed to copy two elements the third time append was called we needed to copy three elements our proof in sect is that equals *( )/ the highest powered term in this formula is the term thereforethe append method in sect exhibits ( complexity this is not really good result the red curve in the graph of fig shows the actual results of how much time it takes to append , elements to pylist the line looks somewhat like the graph of (nn what this tells us is that if we were to draw complex program with say , graphics commands in itto add one more command to the sequence it would take around this is unacceptablewe may never draw anything that complexbut computer should be able to add one more graphic command quicker than thatin terms of big-oh notation we say that the append method is ( when gets largeprograms or functions with ( complexity are not very good you typically want to stay away from writing code that has this kind of computational complexity associated with it unless you are absolutely sure it will never be called on large data sizes one real-world example of this occurred few years ago tester was testing some code and placed cd in cd drive on this computer all the directories and file names on the cd were read into memory and sorted alphabetically the sorting algorithm that was used in that case had ( complexity this was ok because most cds put in this computer had relatively small number of directories and files on them howeveralong came one cd with literally hundreds of thousands of files this copy belongs to 'acha
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 complexity is if we take another look at our pylist append method we might be able to make it more efficient if we didn' have to access each element of the first list when concatenating the two lists the use of the operator is what causes python to access each element of that first list when is used new list is created with space for one more element then all the elements from the old list must be copied to the new list and the new element is added at the end of this list using the append method on lists changes the code to use mutator method to alter the list by adding just one more element it turns out that adding one more element to an already existing list is very efficient in python in factappending an item to list is ( operation as we'll see later in this this means to append items to list we have gone from ( to (nlater in this we'll learn just how python can insure that we get ( complexity for the append operation the blue line in fig shows how the pylist append method works when the operator is replaced by calling the list append method instead at , elements fig the complexity of appending to pylist this copy belongs to 'acha
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(self,item)self items append(item commonly occurring computational complexities the algorithms we will study in this text will be of one of the complexities of ( ) (log ) ( log ) ( )or (cn graph of the shapes of these functions appears in fig most algorithms have one of these complexities corresponding to some factor of constant values added or multiplied to the terms in formula for measuring the time needed to complete computation do not affect the overall complexity of that operation computational complexity is only affected by the highest power term of the equation the complexities graphed in fig are of some power or the log of nexcept for the really awful exponential complexity of (cn )where is some constant value as you are reading the text and encounter algorithms with differing complexitiesthey will be one of the complexities shown in fig as alwaysthe variable represents the size of the data provided as input to the algorithm the time taken to process that data is the vertical axis in the graph while we don' care about the exact numbers in this graphwe do care about the overall shape of these functions the flatter the linethe lower the slopethe better the algorithm performs clearly an algorithm that has exponential complexity ( (cn )or -squared complexity ( ( )complexity will not perform very well except for very small values of if you know your algorithm will never be called for large values of then an inefficient algorithm might be acceptablebut you would have to be really sure that you knew that your data size would always be small typically we want to design algorithms that are as efficient as possible in subsequent you will encounter sorting algorithms that are ( and then you'll learn that we can do better and achieve ( log ncomplexity you'll see search algorithms that are (nand then learn how to achieve (log ncomplexity you'll also learn technique called hashing that will search in ( time the techniques you learn will help you deal with large amounts of data as efficiently this copy belongs to 'acha
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 upper bound on the complexity of an algorithm there we began with an intuitive understanding of the idea of efficiency saying that function exhibits complexity if it is bounded above by function of where represents the size of the data given to the algorithm in this section we further develop these concepts to bound the efficiency of an algorithm from both above and below we begin with an in-depth discussion of efficiency and the measurement of it in computer science when concerning ourselves with algorithm efficiency there are two issues that must be considered this copy belongs to 'acha
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 and other running programs the space that is referred to is the amount of ram needed to solve problem the time we are concerned with is measure of how the number of operations grow as the size of the data grows consider function (nthat is description of the running time of an algorithmwhere is the size of the data given to the algorithm as computer scientists we want to study the asymptotic behavior of this function in other wordswe want to study how (nincreases as the value of is natural number representing possible sizes of input data the natural numbers are the set of non-negative integers the definition in sect is re-statement of the big-oh notation definition presented earlier in this big-oh asymptotic upper bound ( ( ) (nd and we write that (nis ( ( ) (( ( ))and we say that is big-oh of the definition of big-oh says that we can find an upper bound for the time it will take for an algorithm to run consider the plot of time versus data size given in fig data sizeor is the axiswhile time is the axis imagine that the green line represents the observed behavior of some algorithm the blue line clearly is an upper bound to the green line after about this is what the definition of big-oh means for whilethe upper bounding function may not be an upper boundbut eventually it becomes an upper bound and stays that way all the way to the limit as approaches infinity butdoes the blue line represent tight bound on the complexity of the algorithm whose running time is depicted by the green linewe' like to know that when we describe the complexity of an algorithm it is truly representational of the actual running time saying that the algorithm runs in ( is accurate even if the algorithm runs in time proportional to because big-oh notation only describes an upper bound if we truly want to say what the algorithm' running time is proportional tothen we need little more power this leads us to our next definition in sect this copy belongs to 'acha
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 is ( ( )considering our graph once againwe see that the purple line is dominated by the observed behavior sometime after as with the upper boundfor while the lower bound may be greater than the observed behaviorbut after whilethe lower bound stays below the observed behavior for all bigger values of with both lower bound and and upper bound definitionwe now have the notation to define an asymptotically tight bound this is called theta notation theta asymptotic tight bound ( ( ) (nc and if we can find such function gthen we can declare that ( ( )is an asymptotically tight bound for ( )the observed behavior of an algorithm in fig the upper bound blue line is (nn and the lower bound purple line is plot of ( )/ if we let and / we have the asymptotically tight bound of (nat ( nowinstead of saying that -squared is an upper bound on the algorithm' behaviorwe can proclaim that the algorithm truly runs in time proportional to -squared the behavior is bounded above and below by functions of -squared proving the claim that the algorithm is an -squared algorithm amortized complexity sometimes it is not possible to find tight upper bound on an algorithm for instancemost operations may be bounded by some function * (nbut every once in while there may be an operation that takes longer in these cases it may be helpful to employ something called amortized complexity amortization is term used by accountants when spreading the cost of some business transaction over number of years rather than applying the whole expense to the books in one fiscal year this same idea is employed in computer science when the cost of an operation is averaged the key idea behind all amortization methods is to get as tight an upper bound as we can for the worst case running time of any sequence of operations on data structure (which usually starts out emptyby dividing by we get the average or amortized running time of each operation in the sequence this copy belongs to 'acha
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 it is not possible to add to an array in an array can be allocated with fixed sizebut cannot have its size increased once created pretend for moment that python listslike arraysdid not support the append method on lists and that the only way to create list was to write something like [none]* where was fixed value writing [none]* creates fixed size list of elements each referencing the value none this is the way and +arrays are allocated in our examplesince we are pretending that python does not support append we must implement our pylist append method differently we can' use the append method and earlier in this we saw that that adding on item at time with the operator was bad idea we'll do something little different our pylist append operationwhen it runs out of space in the fixed size listwill double the size of the list copying all items from the old list to the new list as shown in the code in sect this copy belongs to 'acha
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 numitems def append(self,item)if self numitems =len(self items)we must make the list bigger by allocating new list and copying all the elements over to the new list newlst [noneself numitems for in range(len(self items))newlst[kself items[ self items newlst self items[self numitemsitem self numitems + def main() pylist( for in range( ) append( print( itemsprint( numitemsprint(len( items) if __name__ ="__main__"main(the claim is thatusing this new pylist append methoda sequence of append operations on pylist objectstarting with an empty listtakes (ntime meaning that individual operations must not take longer than ( time how can this be truewhenever the list runs out of space new list is allocated and all the old elements are copied to the new list clearlycopying elements from one list to another takes longer than ( time understanding how append could exhibit ( complexity relies on computing the amortized complexity of the append operation technicallywhen the list size is doubled the complexity of append is (nbut how often does that happenthe answer is not that often proof of append complexity the proof that the append method has ( complexity uses what is called the accounting method to find the amortized complexity of append the accounting method stores up cyber dollars to pay for expensive operations later the idea is that there must be enough cyber dollars to pay for any operation that is more expensive than the desired complexity this copy belongs to 'acha
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 accounting methodwe'll claim that the cost of doing the append operation requires an additional two cyber dollars this is still ( complexity each time we run out of space we'll double the number of slots in the fixed size list allocating fixed size list is ( operation regardless of the list size the extra work comes when copying the elements from the old list to the new list fig append cyber dollars this copy belongs to 'acha
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 shows the two stored cyber dollars and the result after copying to the new list when moving from step to step when append is called on version of the list the result is version at this pointthree cyber dollars are stored to be used when doubling the list size to four locations the first two are filled with the old contents of the list two of the three stored cyber dollars are used while copying these values to the new list when the list of size four fillstwo additional append operations have occurredstoring five cyber dollars four of these cyber dollars are used in the copy from step to step againwhen the list of size eight fills in step there are nine stored cyber dollars to be used in doubling the list size and copying the elements over butwhat if we didn' double the size of the list each time if we increased the list size by one half its previous size each timewe could still make this argument work if we stored four cyber dollars for each append operation in factas long as the size of the list grows proportionally to its current size each time it is expanded this argument still works to prove that appending to list is ( operation when lists must be allocated with fixed size as mentioned earlierthe python list object is implemented in while python provides an append operationthe language can only allocate fixed size listscalled arrays in and yetpython list objects can append objects in ( time as can be observed by experimentation or by analyzing the code that implements python list objects the python list append implementation achieves this by increasing the list size as described in this section when the fixed size array runs out of space to achieve an amortized complexity of ( summary this covered some important topics related to the efficiency of algorithms efficiency is an important topic because even the fastest computers will not be able to solve problems in reasonable amount of time if the programs that are written for them are inefficient in factsome problems can' be solved in reasonable amount of time no matter how the program is written neverthelessit is important that we understand these issues of efficiency finding the complexity of piece of code is an important skill that you will get better at the more you practice here are some of the things you should have learned in this you shouldknow the complexity of storing or retrieving value from list or the memory of the computer know how memory is like post office know how memory is not like post office this copy belongs to 'acha
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 how it establishes an upper bound on the performance of piece of code understand why the list operation is not as efficient as the append operation understand the difference between ( ) ( )and other computational complexities and why those differences are important to us as computer programmers understand theta notation and what an asymptotically tight bound says about an algorithm understand amortized complexity and how to apply it in some simple situations review questions answer these short answermultiple choiceand true/false questions to test your mastery of the how is list like bunch of post office boxes how is accessing an element of list not like retrieving the contents of post office box how can you compute the amount of time it takes to complete an operation in computer using python in terms of computational complexitywhich is betteran algorithm that is ( or an algorithm that is ( ) describein englishwhat it means for an algorithm to be ( when doing proof by inductionwhat two parts are there to the proof if you had an algorithm with loop that executed steps the first time throughthen the second timen the next timeand kept repeating until the last time through the loop it executed stepswhat would be the complexity measure of this loopjustify your answer with what you learned in this assume you had data set of size and two algorithms that processed that data set in the same way algorithm took steps to process each item in the data set algorithm processed each item in steps what would the complexity be of these two algorithms explain why the append operation on list is more efficient than the operator describe an algorithm for finding particular value in list then give the computational complexity of this algorithm you may make any assumptions you wantbut you should state your assumptions along with your algorithm this copy belongs to 'acha
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 average case complexity write program that produces an xml file with your results in the format specified in this then use the plotdata py program to visualize those results conduct an experiment to prove that the product of two numbers does not depend on the size of the two numbers being multiplied write program that plots the results of multiplying numbers of various sizes together hintto get good reading you may want to do more than one of these multiplications and time them as group since multiplication happens pretty quickly in computer verify that it truly is ( operation do you see any anomaliesit might be explained by python' support of large integers what is the cutoff point for handling multiplications in constant timewhywrite program that produces an xml file with your results in the format given in this then visualize your results with the plotdata py program provided in this write program to gather experimental data about comparing integers compare integers of different sizes and plot the amount of time it takes to do those comparisons plot your results by writing an xml file in the ploy py format is the comparison operation always ( )if notcan you theorize whyhintyou may want to read about python' support for large integers write short function that searches for particular value in list and returns the position of that value in the list ( its indexthen write program that times how long it takes to search for an item in lists of different sizes the size of the list is your gather results from this experiment and write them to an xml file in the plotdata py format what is the complexity of this algorithmanswer this question in comment in your program and verify that the experimental results match your prediction thencompare this with the index method on list which is more efficient in terms of computational complexityhintyou need to be careful to consider the average case for this problemnot just trivial case write short function that given listadds together all the values in the list and returns the sum write your program so it does this operation with varying sizes of lists record the time it takes to find the sum for various list sizes record this information in an xml file in the plotdata py format what complexity is this algorithmanswer this in comment at the top of your program and verify it with your experimental data compare this data with the built-in sum function in python that does the same thing which is more efficient in terms of computational complexityhintyou need to be careful to consider the average case for this problemnot just trivial case assume that you have datatype called the clearable type this data type has fixed size list inside it when it is created so clearable( would create clearable list of size objects of the clearable type should support an append operation and lookup operation the lookup operation is called __getitem__(itemif cl is this copy belongs to 'acha
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 call to append by setting all elements of the list back to none the clearable object should always keep track of the number of values currently stored in the object form theory about the complexity of the append operation on this datatype then write test program to test the clearable object on different initial sizes and numbers of append operations create one sequence for each different initial size of the clearable datatype and write your results in the plot format described in this then comment on how your theory holds up or does not hold up given your experimentation results this copy belongs to 'acha
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 style called imperative programming this simply means that you are likely used to thinking about creating variablesstoring valuesand updating those values as program proceeds in this you are going to begin learning different style of programming called functional programming when you program in the functional styleyou think much more about the definition of what you are programming than how you are going to program it some say that writing recursive functions is declarative approach rather than an imperative approach you'll start to learn what that means for you very soon when you start to get good at writing recursive functions you'll be surprised how easy it can bepython programs are executed by an interpreter an interpreter is program that reads another program as its input and does what it says the python interpreterusually called pythonwas written in language called that program reads python program and does what the python program says to do in its statements an interpreter interprets program by running or executing what is written within it the interpreter interacts with the operating system of the computer to use the networkthe keyboardthe mousethe monitorthe hard driveand any other / device that it needs to complete the work that is described in the program it is interpreting the picture in fig shows you how all these pieces fit together in this we'll introduce you to scopethe run-time stackand the heap so you understand how the interpreter calls functions and where local variables are stored then we'll provide several examples of recursive functions so you can begin to see how they are written there will be number of recursive functions for you to practice writing and we'll apply recursion to drawing pictures as well one thing you will not do in the homework for this is write code that uses for loop or while loop if you find yourself trying to write code that uses either kind of loop you are trying to write function imperatively rather than functionally (cspringer international publishing switzerland lee and hubbarddata structures and algorithms with pythonundergraduate topics in computer sciencedoi -- this copy belongs to 'acha
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 function is calledwhat happens to the run-time stack when function returns from callwhat are the two important parts to recursive function and which part comes firstexactly what happens when return statement is executedwhy should we write recursive functionswhat are the computational complexities of various recursive functionsyou should also be able to write some simple recursive functions yourself without thinking too hard about how they work in additionyou should be able to use debugger to examine the contents of the run-time stack for recursive function this copy belongs to 'acha
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 the reference that is pointing at it for instanceif we writex it means that is reference that points to an object with inside it but sometimes we are careless and just say that equals it is important that you understand that even when we say things like equals what we really mean is that is reference that points to an object that contains you can see why we are careless sometimes it takes too many words to say what we really mean and as long as everyone understands that references have names and objects are pointed to by referencesthen we can save the words the rest of this text will make this assumption at times when it is really importantwe'll make sure we distinguish between references and objects part of our mental picture must include scope in python program scope refers to part of program where collection of identifiers are visible let' look at simple example program local scope consider the code in fig in this program there are several scopes every colored region of the figure delimits one of those scopes while executing line of the program in fig the light green region is called the local scope the local scope is the scope of the function that the computer is currently executing when your program is executing line of codethe scope that surrounds that line of code is called the local scope when you reference an identifier in statement in your programpython first examines the local scope to see if the identifier is defined therewithin the local scope an identifieridis defined under one of three conditions statement like id appears somewhere within the current scope in this case id would be reference to an object in the local scope id appears as parameter name of the function in the current scope in this case id would be reference to an object that was passed to the current function as an argument id appears as name of function or class through the use of function def or class definition within the current scope while python is executing line in fig the reference val is defined within its local scope if python finds id in the local scopeit looks up the corresponding value and retrieves it this is what happens when val is encountered on line the object that is referenced by val is retrieved and returned this copy belongs to 'acha
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 identifiers defined in this enclosing scope include historyofpromptshistoryofoutputrstringrvalgetinputand showinput notice that function names are included as identifiers againpython looks for the identifier using the same this copy belongs to 'acha
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 defined in the enclosing scope and retrieves it for use in the call to the append method which scope is local depends on where your program is currently executing when executing line the light green region is the local scope when executing line the brown region is the local scope when executing line or line the purple region is the local scope when executing line the darker green region is the local scope finallywhen executing line or the blue region is the local scope the local scope is determined by where your program is currently executing scopes are nested this means that each scope is nested inside another scope the final enclosing scope of module is the module itself each module has its own scope the blue region of fig corresponds to the module scope identifiers that are defined outside of any other functionsbut inside the moduleare at the module level the reference pi in fig is defined at the module level the functions area and main are also defined at the module level scope while executing line of the program in fig the identifier val is defined in the local scope butval is also defined in the enclosing scope this is acceptable and often happens in python programs each scope has its own copy of identifiers the choice of which val is visible is made by always selecting the innermost scope that defines the identifier while executing line of the program in fig the val in the local scope is visible and the val in the enclosing scope is hidden this is why it is important that we choose our variable names and identifiers carefully in our programs if we use an identifier that is already defined in an outer scopewe will no longer be able to access it from an inner scope where the same identifier is defined it is relatively easy to determine all the nested scopes within module every function definition (including the definition of methodswithin module defines different scope the scope never includes the function name itselfbut includes its parameters and the body of the function you can follow this pattern to mentally draw boxes around any scope so you know where it begins and ends in your code global scope using python it is possible to define variables at the global level generally this is bad programming practice and we will not do this in this text if interested you can read more about global variables in python online butusing too many global variables will generally lead to name conflicts and will likely lead to unwanted side effects poor use of global variables contributes to spaghetti code which is named for the big mess you would have trying to untangle it to figure out what it does this copy belongs to 'acha
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 were to write the followingx int(" "python would first look in the local scope to see if int were defined as function or variable within that local scope if int is not found within the local scopepython would look in all the enclosing scopes starting with the next inner-most local scope and working outwards from there if not found in any of the enclosing scopespython would then look in the global scope for the int identifier if not found therethen python would consult the built-in scopewhere it would find the int class or type with this explanationit should now be clear why you should not use identifiers that already exist in the built-in scope if you use int as an identifier you will not be able to use the int from the built-in scope because python will find int in local or enclosing scope first legb mark lutzin his book learning python [ ]described the rules of scope in python programs using the legb acronym this acronymstanding for localenclosingglobaland built-in can help you memorize the rules of scope in python the order of the letters in the acronym is important when the python interpreter encounters an identifier in programit searches the local scope firstfollowed by all the enclosing scopes from the inside outwardfollowed by the global scopeand finally the built-in scope the run-time stack and the heap as we learned in the last sectionthe parameters and body of each function define scope within python program the parameters and variables defined within the local scope of function must be stored someplace within the ram of computer python splits the ram up into two parts called the run-time stack and the heap the run-time stack is like stack of trays in cafeteria most cafeterias have device that holds these trays when the stack of trays gets short enough spring below the trays pops the trays up so they are at nice height as more trays are added to the stackthe spring in this device compresses and the stack pushes down stack in computer science is similar in many ways to this kind of device the run-time stack is stack of activation records the python interpreter pushes an activation this copy belongs to 'acha
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 new activation record is pushed onto the run-time stack this new activation record holds all the variables that are defined within the new local scope when function returns its corresponding activation record is popped from the run-time stack the heap is the area of ram where all objects are stored when an object is created it resides in the heap the run-time stack never contains objects references to objects are stored within the run-time stack and those references point to objects in the heap consider the program in fig when the python interpreter is executing lines and of the programthe run-time stack looks as it does in fig there are three activation records on the run-time stack the first activation record pushed onto the run-time stack was for the module when the module first began executingthe python interpreter went through the module from top to bottom and put any variable definitions in the module scope into the activation record for the module in this program that consisted of the reference pi to the value thenat the end of the module the if statement called the main function this caused the python interpreter to push the activation record for the main function the variables defined within the main function include historyofpromptshistoryofoutputrstringrand val each of these appear within the activation record for the main function as the main function began executing it called the getinput function when that call occurred there was an activation record pushed for the function call that activation record contained the prompt and variables this activation record does not appear in the figure because by the time we execute line and of the program the python interpreter has already returned from the getinput function when the interpreter returned from the function call the corresponding activation record was popped from the run-time stack finallythe program calls the showoutput function on line and execution of the function begins an activation record for the showoutpout function call was pushed onto the run-time stack when showoutput was called the references local to that scopewhich includes just the val variablewere stored the activation record for this function call you can run this example program using wing or some other ide the code for it appears in sect when you use the wing ide to run this program you can stop the program at any point and examine the run-time stack for instancefig shows wing in the midst of running this program breakpoint has been set on line to stop the program the tab at the bottom of the wing ide window shows the stack data this is the run-time stack right below the stack data tab there is combination box that currently displays showoutput()scope pyline this combo box lets you pick from the activation record that is currently being displayed if you pick different activation recordits contents will be displayed directly below it in the wing ide this copy belongs to 'acha
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 implemented the reference for this variable shows up in the activation record for showoutput because it is being referenced from this scope butthe reference to historyofoutput in the activation record for showoutput and the reference called historyofoutput in the main activation record point at the same object so no real harm is done the important thing to note is that the wing ide is correct in showing the historyofoutput variable as local variable in this activation record since this is reflection of python' implementation and not due to bug in wing ide this copy belongs to 'acha
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 would never finish actuallyit would finish when run on computer because we just learned that every time you call functionan activation record is pushed on the run-time stack if recursive function continues to call itself over and over it will this copy belongs to 'acha
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 between inductive proofs and recursive functions the base case in recursive function must be written firstbefore the function is called recursively nowwrapping your head around just how recursive function works is little difficult at first actuallyunderstanding how recursive function works isn' all that important when writing recursive functions we want to think more about what it does than how it works it doesn' pay to think too hard about how recursive functions workbut in fact even that will get much easier with some practice when writing recursive function there are four rules that you adhere to these rules are not negotiable and will ensure that your recursive function will eventually finish if you memorize and learn to follow these rules you will be writing recursive functions in no time the rules are decide on the name of your function and the arguments that must be passed to it to complete its work as well as what value the function should return write the base case for your recursive function first the base case is an if statement that handles very simple case in the recursive function by returning value finallyyou must call the function recursively with an argument or arguments that are smaller in some way than the parameters that were passed to the function when the last call was made the argument or arguments that get smaller are the same argument or arguments you examined in your base case look at concrete example pick some values to try out with your recursive function trust that the recursive call you made in the last step works take the result from that recursive call and use it to form the result you want your function to return use the concrete example to help you see how to form that result we'll do very simple example to begin with in the last we proved the following ( = soif we wanted to compute the sum of the first integerswe could write python program as shown in sect sum of integers def sumfirstn( )return ( + / def main()this copy belongs to 'acha
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 on the size of the datan howeverto illustrate recursive functionlet' go back to the definition of summation the definition for summation has two parts firstthe base case of the definition = = the recursive part of the definition is as follows this is what we call recursive definition because it is defined in terms of itself notice that the recursive definition is defined in terms of smaller nin this case the summation to is our recursive call and it will work if we want to compute the sum of the first integersthen the recursive call computes to give us adding will give use the result we want  - + ii= = the two parts of this recursive definition can be translated directly into recursive function in python the recursive definition is given in sect recursive sum of integers def recsumfirstn( )if = return elsereturn recsumfirstn( - def main() int(input("please enter non-negative integer") recsumfirstn( print("the sum of the first" "integers is"str( )+" if __name__ ="__main__"main(the recsumfirstn function in the code of sect is recursive it calls itself with smaller value and it has base case that comes firstso it is well-formed there is this copy belongs to 'acha
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 function is not executed if is not zerothen we want to execute the code on the else statement this means we could rewrite this function as shown in sect no else needed def recsumfirstn( )if = return return recsumfirstn( - the format of the code in sect is common way to write recursive functions sometimes recursive function has more than one base case each base case can be handled by an if statement with return in it the recursive case does not need to be in an else when all base cases result in return the recursive case comes last in the recursive function definition tracing the execution of recursive function early in this you were given the mandate "don' think too hardwhen writing recursive function understanding exactly how recursive function works may be bit difficult when you are first learning about them it may help to follow the execution of recursive function in an example consider the program in the previous section let' assume that the user entered the integer at the keyboard when this program begins running it will have an activation record on the run-time stack for the module and the main function when the program gets to line in the code of sect where the recsumfirstn function is first calleda new activation record will be pushed for the function callresulting in three activation records on the run-time stack the python interpreter then jumps to line with pointing at the number as shown in the picture of fig execution of the function proceeds the value of is not zeroso python executes line where there is another function call to recsumfirstn this causes the python interpreter to push another activation record on the run-time stack and the interpreter jumps to line again this time the value of is but againthis is not zeroso line is executed and another activation record is pushed with new value of for this repeats two more times for values of and for the important thing to note in this program execution is that there is one copy of the variable for each recursive function call an activation record holds the local variables and parameters of all variables that are in the local scope of the function this copy belongs to 'acha
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 the python interpreter finds that equals on line of the code it is at this point that the sumfirstn function returns its first value it returns to the previous function call where was the return occurs on line of the code the activation record for the function call when was is popped from the run-time stack this is depicted in fig by the shading of the activation record in the figure when the function returns the space for the activation record is reclaimed for use later the shaded this copy belongs to 'acha
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 return statement as well sothe function returns again againit returns to line but this time with value of the function returns againbut with value of this time againsince it returned to line the function returns again with value of finallyonce again the function returnsthis time with value of but this time the recsumfirstn function returns to line of the main function where is made to point to the value of this is depicted in fig this copy belongs to 'acha
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 the scope of the recsumfirstn function each time the function is calledthe local variables and parameters are copied into the corresponding activation record when function call returnsthe corresponding activation record is popped off the run-time stack this is how recursive function is executed this copy belongs to 'acha
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 #each time for nice color effect if length = return add ^ to the old color modulo ^ the modulo ^ prevents the color from getting too big newcolor (int(color[ :], ** )%( ** find the color base integer value base int(colorbase[ :], now if the new color is less than the base add the base modulo ^ if newcolor basenewcolor (newcolor base)%( ** let newcolor be the hex string after conversion newcolor hex(newcolor)[ : add pound sign and zeroes to the front so it is characters long plus the pound sign for proper color string newcolor "#"+(" "*( -len(newcolor)))+newcolor color(newcolort forward(lengtht left( drawspiral(tlength- newcolorcolorbase def main() turtle turtle(screen getscreen( speed( penup( goto(- ,- pendown( drawspiral( "# ""#ff ff" screen exitonclick( this copy belongs to 'acha
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 complex part of the code there is some slicing going on there to convert the color string from hexadecimal string to an integer so can be addedmodulo to the th then it must be converted back to hexadecimal color string with the "#ffffffformat the program draws spiral like the one pictured in fig notice that this recursive function does not return anything most recursive functions do return value this one does not because the purpose of the function is to draw spiral it has side-effect instead of returning value recursion on lists and strings recursive functions can be written for many different purposes many problems can be solved by solving simpler problem and then applying that simpler solution recursively for instanceconsider trying to write function that returns the reverse of list if we wrote this non-recursivelywe might write it as follows list recursion def revlist(lst)accumulator [this copy belongs to 'acha
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 learned to program imperatively if we think about the problem recursivelywe would first consider how to reverse very simple listsay the empty list the reverse of the empty list is just the empty list once we have solved the problem for very simple listwe can assume that if we call recursive reverse function on something smaller ( shorter list)it will work sothen to complete recursive solutionwe have only to piece our solution together recursive solution to reversing list is found in sect reversing list def revlist(lst)here is the base case if lst =[]return [ the rest of this function is the recursive case this works because we called it on something smaller the lst[ :is slice of all but the first item in lst restrev revlist(lst[ :]first lst[ : now put the pieces together result restrev first return result def main()print(revlist([ , , , ]) if __name__ ="__main__"main(you can write recursive functions that work with strings too strings and lists are both sequences in the code of sect we made sure we recursively called our function on something smaller the same is true when working with strings string reverse function is given in sect this copy belongs to 'acha
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 definition of reverse did not change the only change is that we must use the string concatenation operator instead of the list concatenation operator and the empty string instead of the empty list another version of reverse def revlist (lst) def revlisthelper(index)if index =- return [ restrev revlisthelper(index- first [lst[index] now put the pieces together result first restrev return result this is the one line of code for the revlist function return revlisthelper(len(lst)- def main()print(revlist ([ , , , ]) if __name__ ="__main__"main(the examples in sects and used slicing to make the list or string smaller on each recursive call it is possible to make list or string smaller without actually making it physically smaller using an index to keep track of your position this copy belongs to 'acha
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 the helper function insteadthe index argument gets smallercounting down to - when the empty list is returned the revlist function contains only one line of code to call the revlisthelper function because the revlisthelper function is nested inside revlist the helper function is not visible to anything but the revlist function since we don' want other programmers to call the helper function except by calling the revlist function first it is important to note that you don' have to physically make list or string smaller to use it in recursive function as long as indexing is available to youa recursive function can make use of an index into list or string and the index can get smaller on each recursive call one other thing to note in this example the index gets smaller by approaching zero on each recursive call there are other ways for the argument to the recursive function to get smaller for instancethis example could be rewritten so the index grows toward the length of the list in that case the distance between the index and the length of the list is the value that would get smaller on each recursive call using type reflection many of the similarities in the two functions of sects and are due to operator overloading in python python has another very nice feature called reflection reflection refers to the ability for code to be able to examine attributes about objects that might be passed as parameters to function one interesting aspect of reflection is the ability to see what the type of an object is if we write type(objthen python will return an object which represents the type of obj for instanceif obj is reference to stringthen python will return the str type object furtherif we write str(we get string which is the empty string in other wordswriting str(is the same thing as writing "likewisewriting list(is the same thing as writing [using reflectionwe can write one recursive reverse function that will work for stringslistsand any other sequence that supports slicing and concatenation recursive version of reverse that will reverse both strings and lists is provided in sect reflection reverse def reverse(seq)seqtype type(seqemptyseq seqtype( this copy belongs to 'acha
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 to reverse any sequence it is polymorphic due to reflection and operator overloading pretty neat stuff summary in this you were introduced to some concepts that are important to your understanding of algorithms to be presented later in this text understanding how the run-time stack and the heap work to make it possible to call functions in our programs will make you better programmer forming mental model of how our code works makes it possible to predict what our code will do writing recursive functions is also skill that is important to computer programmers here is what you should have learned in this you shouldbe able to identify the various scopes within program be able to identify which scope variable reference belongs tothe localenclosingglobalor built-in scope remember the legb rule be able to trace the execution of program by drawing picture of the run-time stack and the heap for program as it executes be able to write simple recursive function by writing base case and recursive case where the function is called with smaller value be able to trace the execution of recursive functionshowing the run-time stack and heap as it executes understand little about reflection as it relates to examining types in python code this copy belongs to 'acha
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 inspected to see where or if variable is defined pick sample program from among the programs you have writtenpreferably short oneand identify three scopes within it by drawing box around the scopes when is an activation record pushed onto the run-time stack when is an activation record popped from the run-time stack what goes in the heap in computer what goes in an activation record on the run-time stack when writing recursive functionwhat are the two cases for which you must write code if recursive function did not have base casewhat would happen when it was called what must be true of the recursive call in recursive functionin other wordswhat must you ensure when making this recursive call what does the type function return in pythonif you call the type function in programwhat aspect of python are you using programming problems write recursive function called intpow that given numberxand an integernwill compute you must write this function recursively to get full credit be sure to put it in program with several test cases to test that your function works correctly write recursive function to compute the factorial of an integer the factorial of is the factorial of any integerngreater than zero is times the factorial of - write program that tests your factorial function by asking the user to enter an integer and printing the factorial of that integer be sure your program has main function comment your code with the base case and recursive case in your recursive function write recursive function that computes the length of string you cannot use the len function while computing the length of the string you must rely on the function you are writing put this function in program that prompts the user to enter string and then prints the length of that string this copy belongs to 'acha
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 drawbranch pass it turtle to draw withan angleand the number of littler branches to draw like the tree that appears in fig each time you recursively call this function you can decrease the number of branches and the angle each littler branch is drawn at some angle from the current branch so your function can change the angle of the turtle by turning left or right when your number of branches gets to zeroyou can draw leaf as little green square if you make the width of the turtle line thicker for bigger branches and smaller for littler branchesyou'll get nice tree you might write one more function called drawtree that will set up everything (except the turtleto draw nice tree put this function in program that draws at least one tree hintin your drawbranch functionafter you have drawn the branch (and all sub-branchesyou will want to return the turtle to the original position and direction you started at this is necessary so after calling drawbranch you will know where the turtle is located if you don' return it to its original positionthe turtle will end up stranded out at leaf somewhere write recursive function that draws circular spiral to do thisyou'll need to use polar coordinates polar coordinates are way of specifying any point in the plane with an angle and radius zero degrees goes to the right and the angles go counter-clockwise in circle with an angle and radiusany point in the plane can be described to convert an angleaand radiusrfrom polar coordinates to cartesian coordinates you would use sine and cosine you must import the math module then math cos (aand math sin (athis copy belongs to 'acha
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 pass an ( ,ycoordinate to the drawspiral function for the center point of your spiral thenany coordinates you compute will be added to the center ( ,yyou can follow the square spiral example in the text put this code in program that draws spiral to the screen write program to gather performance data for the reverse function found in this write an xml file in the plot format found in this text to visualize that performance data because this function is recursivekeep your data size small and just gather data for string sizes of - this will help you visualize your result what is the complexity of this reverse functionput comment at the top of your program stating the complexity of reverse in big-oh notation justify your answer by analyzing the code found in the reverse function rewrite the program in sect to use an index that approaches the length of the list instead of an index that approaches zero then write main function that thoroughly tests your new reverse function on lists you must test it on both simple and more complex examples of lists to test it thoroughly this copy belongs to 'acha