id
int64
0
25.6k
text
stringlengths
0
4.59k
12,700
notice that the print_exp function as we have implemented it puts parentheses around each number while not incorrectthe parentheses are clearly not needed in the exercises at the end of this you are asked to modify the print_exp function to remove this set of parentheses binary search trees we have already seen two different ways to get key-value pairs in collection recall that these collections implement the map abstract data type the two implementations of map adt we discussed were binary search on list and hash tables in this section we will study binary search trees as yet another way to map from key to value in this case we are not interested in the exact placement of items in the treebut we are interested in using the binary tree structure to provide for efficient searching search tree operations before we look at the implementationlet' review the interface provided by the map adt you will notice that this interface is very similar to the python dictionary map(create newempty map put(key,valadd new key-value pair to the map if the key is already in the map then replace the old value with the new value get(keygiven keyreturn the value stored in the map or none otherwise del delete the key-value pair from the map using statement of the form del map[keylen(return the number of key-value pairs stored in the map in return true for statement of the form key in mapif the given key is in the map search tree implementation binary search tree relies on the property that keys that are less than the parent are found in the left subtreeand keys that are greater than the parent are found in the right subtree we will call this the bst property as we implement the map interface as described abovethe bst property will guide our implementation figure illustrates this property of binary search treeshowing the keys without any associated values notice that the property holds for each parent and child all of the keys in the left subtree are less than the key in the root all of the keys in the right subtree are greater than the root now that you know what binary search tree iswe will look at how binary search tree is constructed the search tree in figure represents the nodes that exist after we have inserted the following keys in the order shown since was the first key inserted into the treeit is the root next is less than so it becomes the left child of next is greater than so it becomes the right child of now we have two levels of binary search trees
12,701
figure simple binary search tree the tree filledso the next key is going to be the left or right child of either or since is greater than and it becomes the right child of similarly is less than and so it becomes the left child of is also less than so it must be in the left subtree of howeverit is greater than so it becomes the right child of to implement the binary search treewe will use the nodes and references approach similar to the one we used to implement the linked listand the expression tree howeverbecause we must be able create and work with binary search tree that is emptyour implementation will use two classes the first class we will call binarysearchtreeand the second class we will call treenode the binarysearchtree class has reference to the treenode that is the root of the binary search tree in most cases the external methods defined in the outer class simply check to see if the tree is empty if there are nodes in the treethe request is just passed on to private method defined in the binarysearchtree class that takes the root as parameter in the case where the tree is empty or we want to delete the key at the root of the treewe must take special action the code for the binarysearchtree class constructor along with few other miscellaneous functions is shown below basic binarysearchtree class incomplete class binarysearchtreedef __init__(self)self root none self size def length(self)return self size def __len__(self)return self size def __iter__(self)return self root __iter__(the treenode class provides many helper functions that make the work done in the binarysearchtree class methods much easier the constructor for treenodealong trees and tree algorithms
12,702
with these helper functionsis shown below as you can see in the code many of these helper functions help to classify node according to its own position as child(left or rightand the kind of children the node has the treenode class will also explicitly keep track of the parent as an attribute of each node you will see why this is important when we discuss the implementation for the del operator completed treenode class class treenodedef __init__(selfkeyvalleft noneright noneparent none)self key key self payload val self left_child left self right_child right self parent parent def has_left_child(self)return self left_child def has_right_child(self)return self right_child def is_left_child(self)return self parent and self parent left_child =self def is_right_child(self)return self parent and self parent right_child =self def is_root(self)return not self parent def is_leaf(self)return not (self right_child or self left_childdef has_any_children(self)return self right_child or self left_child def has_both_children(self)return self right_child and self left_child def replace_node_data(selfkeyvaluelcrc)self key key self payload value self left_child lc self right_child rc if self has_left_child()self left_child parent self if self has_right_child()self right_child parent self binary search trees
12,703
another interesting aspect of the implementation of treenode is that we use python' optional parameters optional parameters make it easy for us to create treenode under several different circumstances sometimes we will want to construct new treenode that already has both parent and child with an existing parent and childwe can pass parent and child as parameters at other times we will just create treenode with the key value pairand we will not pass any parameters for parent or child in this casethe default values of the optional parameters are used now that we have the binarysearchtree shell and the treenode it is time to write the put method that will allow us to build our binary search tree the put method is method of the binarysearchtree class this method will check to see if the tree already has root if there is not root then put will create new treenode and install it as the root of the tree if root node is already in place then put calls the privaterecursivehelper function _put to search the tree according to the following algorithmstarting at the root of the treesearch the binary tree comparing the new key to the key in the current node if the new key is less than the current nodesearch the left subtree if the new key is greater than the current nodesearch the right subtree when there is no left (or rightchild to searchwe have found the position in the tree where the new node should be installed to add node to the treecreate new treenode object and insert the object at the point discovered in the previous step below we show the python code for inserting new node in the tree the _put function is written recursively following the steps outlined above notice that when new child is inserted into the treethe current_node is passed to the new tree as the parent one important problem with our implementation of insert is that duplicate keys are not handled properly as our tree is implemented duplicate key will create new node with the same key value in the right subtree of the node having the original key the result of this is that the node with the new key will never be found during search better way to handle the insertion of duplicate key is for the value associated with the new key to replace the old value we leave fixing this bug as an exercise for you def put(selfkeyval)if self rootself _put(keyvalself rootelseself root treenode(keyvalself size self size def _put(selfkeyvalcurrent_node)if key current_node keyif current_node has_left_child()self _put(keyvalcurrent_node left_childelsecurrent_node left_child treenode(keyvalparent=current_nodeelseif current_node has_right_child() trees and tree algorithms
12,704
figure inserting node with key self _put(keyvalcurrent_node right_childelsecurrent_node right_child treenode(keyvalparent=current_nodewith the put method definedwe can easily overload the [operator for assignment by having the __setitem__ method call the put method this allows us to write python statements like my_zip_tree['plymouth' just like python dictionary def __setitem__(selfkv)self put(kvfigure illustrates the process for inserting new node into binary search tree the lightly shaded nodes indicate the nodes that were visited during the insertion process self check which of the trees shows correct binary search tree given that the keys were inserted in the following order binary search trees
12,705
once the tree is constructedthe next task is to implement the retrieval of value for given key the get method is even easier than the put method because it simply searches the tree recursively until it gets to non-matching leaf node or finds matching key when matching key is foundthe value stored in the payload of the node is returned below we show the code for get_get and __getitem__ the search code in the _get method uses the same logic for choosing the left or right child as the _put method notice that the _get method returns treenode to getthis allows _get to be used as flexible helper method for other binarysearchtree methods that may need to make use of other data from the treenode besides the payload by implementing the __getitem__ method we can write python statement that looks just like we are accessing dictionarywhen in fact we are using binary search treefor example my_zip_tree['fargo'as you can seeall the__getitem__ method does is call get def get(self,key)if self rootres self _get(keyself rootif resreturn res payload elsereturn none elsereturn none def _get(selfkeycurrent_node)if not current_nodereturn none elif current_node key =keyreturn current_node trees and tree algorithms
12,706
elif key current_node keyreturn self _get(keycurrent_node left_childelsereturn self _get(keycurrent_node right_childdef __getitem__(selfkey)return self get(keyusing getwe can implement the in operation by writing __contains__ method for the binarysearchtree the __contains__ method will simply call get and return true if get returns valueor false if it returns none the code for __contains__ is shown below def __contains__(selfkey)if self _get(keyself root)return true elsereturn false recall that __contains__ overloads the in operator and allows us to write statements such asif 'northfieldin my_zip_treeprint("oom ya ya"finallywe turn our attention to the most challenging method in the binary search treethe deletion of key the first task is to find the node to delete by searching the tree if the tree has more than one node we search using the _get method to find the treenode that needs to be removed if the tree only has single nodethat means we are removing the root of the treebut we still must check to make sure the key of the root matches the key that is to be deleted in either case if the key is not found the del operator raises an error def delete(selfkey)if self size node_to_remove self _get(keyself rootif node_to_removeself remove(node_to_removeself size self size elseraise keyerror('errorkey not in tree'elif self size = and self root key =keyself root none self size self size elseraise keyerror('errorkey not in tree'def __delitem__(selfkey)self delete(keyonce we've found the node containing the key we want to deletethere are three cases that we must consider binary search trees
12,707
figure deleting node node without children the node to be deleted has no children (see figure the node to be deleted has only one child (see figure the node to be deleted has two children (see figure the first case is straightforward if the current node has no children all we need to do is delete the node and remove the reference to this node in the parent the code for this case is shown in here if current_node is_leaf()if current_node =current_node parent left_childcurrent_node parent left_child none elsecurrent_node parent right_child none the second case is only slightly more complicated if node has only single childthen we can simply promote the child to take the place of its parent the code for this case is shown below as you look at this code you will see that there are six cases to consider since the cases are symmetric with respect to either having left or right child we will just discuss the case where the current node has left child the decision proceeds as follows if the current node is left child then we only need to update the parent reference of the left child to point to the parent of the current nodeand then update the left child reference of the parent to point to the current node' left child if the current node is right child then we only need to update the parent reference of the right child to point to the parent of the current nodeand then update the right child reference of the parent to point to the current node' right child if the current node has no parentit must be the root in this case we will just replace the key,payloadleft_childand right_child data by calling the replace_node_data method on the root elsethis node has one child trees and tree algorithms
12,708
figure deleting node node that has single child if current_node has_left_child()if current_node is_left_child()current_node left_child parent current_node parent current_node parent left_child current_node left_child elif current_node is_right_child()current_node left_child parent current_node parent current_node parent right_child current_node left_child elsecurrent_node replace_node_data(current_node left_child keycurrent_node left_child payloadcurrent_node left_child left_childcurrent_node left_child right_childelseif current_node is_left_child()current_node right_child parent current_node parent current_node parent left_child current_node right_child elif current_node is_right_child()current_node right_child parent current_node parent current_node parent right_child current_node right_child elsecurrent_node replace_node_data(current_node right_child keycurrent_node right_child payloadcurrent_node right_child left_childcurrent_node right_child right_childthe third case is the most difficult case to handle if node has two childrenthen it is unlikely that we can simply promote one of them to take the node' place we canhoweversearch the tree for node that can be used to replace the one scheduled for deletion what we need is node that will preserve the binary search tree relationships for both of the existing left and right subtrees the node that will do this is the node that has the next-largest key in the tree we call this node the successorand we will look at way to find the successor shortly the successor is guaranteed to have no more than one childso we know how to remove it using the two cases for deletion that we have already implemented once the successor has been removed binary search trees
12,709
figure deleting node node with two children we simply put it in the tree in place of the node to be deleted the code to handle the third case is shown below notice that we make use of the helper methods find_successor and find_min to find the successor to remove the successorwe make use of the method splice_out the reason we use splice_out is that it goes directly to the node we want to splice out and makes the right changes we could call delete recursivelybut then we would waste time re-searching for the key node elif current_node has_both_children()#interior succ current_node find_successor(succ splice_out(current_node key succ key current_node payload succ payload the code to find the successor is shown below and as you can see is method of the treenode class this code makes use of the same properties of binary search trees that cause an inorder traversal to print out the nodes in the tree from smallest to largest there are three cases to consider when looking for the successor if the node has right childthen the successor is the smallest key in the right subtree if the node has no right child and is the left child of its parentthen the parent is the successor if the node is the right child of its parentand itself has no right childthen the successor to this node is the successor of its parentexcluding this node the first condition is the only one that matters for us when deleting node from binary search tree howeverthe find_successor method has other uses that we will explore in the exercises at the end of this trees and tree algorithms
12,710
the find_min method is called to find the minimum key in subtree you should convince yourself that the minimum valued key in any binary search tree is the leftmost child of the tree therefore the find_min method simply follows the left_child references in each node of the subtree until it reaches node that does not have left child def find_successor(self)succ none if self has_right_child()succ self right_child find_min(elseif self parentif self is_left_child()succ self parent elseself parent right_child none succ self parent find_successor(self parent right_child self return succ def find_min(self)current self while current has_left_child()current current left_child return current def splice_out(self)if self is_leaf()if self is_left_child()self parent left_child none elseself parent right_child none elif self has_any_children()if self has_left_child()if self is_left_child()self parent left_child self left_child elseself parent right_child self left_child self left_child parent self parent elseif self is_left_child()self parent left_child self right_child elseself parent right_child self right_child self right_child parent self parent we need to look at one last interface method for the binary search tree suppose that we would like to simply iterate over all the keys in the tree in order this is definitely something we have done with dictionariesso why not treesyou already know how to traverse binary tree in orderusing the inorder traversal algorithm howeverwriting an iterator requires bit more worksince an iterator should return only one node each time the iterator is called binary search trees
12,711
python provides us with very powerful function to use when creating an iterator the function is called yield yield is similar to return in that it returns value to the caller howeveryield also takes the additional step of freezing the state of the function so that the next time the function is called it continues executing from the exact point it left off earlier functions that create objects that can be iterated are called generator functions the code for an inorder iterator of binary tree is shown below look at this code carefullyat first glance you might think that the code is not recursive howeverremember that __iter__ overrides the for in operation for iterationso it really is recursivebecause it is recursive over treenode instances the __iter__ method is defined in the treenode class def __iter__(self)if selfif self has_left_child()for elem in self left_childyield elem yield self key if self has_right_child()for elem in self right_childyield elem at this point you may want to download the entire file containing the full version of the binarysearchtree and treenode classes complete binarysearchtree implementation class treenodedef __init__(selfkeyvalleft noneright noneparent none)self key key self payload val self left_child left self right_child right self parent parent def has_left_child(self)return self left_child def has_right_child(self)return self right_child def is_left_child(self)return self parent and self parent left_child =self def is_right_child(self)return self parent and self parent right_child =self def is_root(self)return not self parent trees and tree algorithms
12,712
def is_leaf(self)return not (self right_child or self left_childdef has_any_children(self)return self right_child or self left_child def has_both_children(self)return self right_child and self left_child def replace_node_data(selfkeyvaluelcrc)self key key self payload value self left_child lc self right_child rc if self has_left_child()self left_child parent self if self has_right_child()self right_child parent self class binarysearchtreedef __init__(self)self root none self size def length(self)return self size def __len__(self)return self size def put(selfkeyval)if self rootself _put(keyvalself rootelseself root treenode(key,valself size self size def _put(selfkeyvalcurrent_node)if key current_node keyif current_node has_left_child()self _put(keyvalcurrent_node left_childelsecurrent_node left_child treenode(keyvalparent current_nodeelseif current_node has_right_child()self _put(keyvalcurrent_node right_childelsecurrent_node right_child treenode(keyvalparent current_node binary search trees
12,713
def __setitem__(selfkv)self put(kvdef get(selfkey)if self rootres self _get(keyself rootif resreturn res payload elsereturn none elsereturn none def _get(selfkeycurrent_node)if not current_nodereturn none elif current_node key =keyreturn current_node elif key current_node keyreturn self _get(keycurrent_node left_childelsereturn self _get(keycurrent_node right_childdef __getitem__(selfkey)return self get(keydef __contains__(selfkey)if self _get(keyself root)return true elsereturn false def delete(selfkey)if self size node_to_remove self _get(keyself rootif node_to_removeself remove(node_to_removeself size self size elseraise keyerror('errorkey not in tree'elif self size = and self root key =keyself root none self size self size elseraise keyerror('errorkey not in tree'def __delitem__(selfkey)self delete(keydef splice_out(self) trees and tree algorithms
12,714
if self is_leaf()if self is_left_child()self parent left_child none elseself parent right_child none elif self has_any_children()if self has_left_child()if self is_left_child()self parent left_child self left_child elseself parent right_child self left_child self left_child parent self parent elseif self is_left_child()self parent left_child self right_child elseself parent right_child self right_child self right_child parent self parent def find_successor(self)succ none if self has_right_child()succ self right_child find_min(elseif self parentif self is_left_child()succ self parent elseself parent right_child none succ self parent find_successor(self parent right_child self return succ def find_min(self)current self while current has_left_child()current current left_child return current def remove(selfcurrent_node)if current_node is_leaf()#leaf if current_node =current_node parent left_childcurrent_node parent left_child none elsecurrent_node parent right_child none elif current_node has_both_children()interior succ current_node find_successor(succ splice_out(current_node key succ key current_node payload succ payload binary search trees
12,715
elsethis node has one child if current_node has_left_child()if current_node is_left_child()current_node left_child parent current_node parent current_node parent left_child current_node left_child elif current_node is_right_child()current_node left_child parent current_node parent current_node parent right_child current_node left_child elsecurrent_node replace_node_data(current_node left_child keycurrent_node left_child payloadcurrent_node left_child left_childcurrent_node left_child right_childelseif current_node is_left_child()current_node right_child parent current_node parent current_node parent left_child current_node right_child elif current_node is_right_child()current_node right_child parent current_node parent current_node parent right_child current_node right_child elsecurrent_node replace_node_data(current_node right_child keycurrent_node right_child payloadcurrent_node right_child left_childcurrent_node right_child right_childmy_tree binarysearchtree(my_tree[ "redmy_tree[ "bluemy_tree[ "yellowmy_tree[ "atprint(my_tree[ ]print(my_tree[ ]search tree analysis with the implementation of binary search tree now completewe will do quick analysis of the methods we have implemented let' first look at the put method the limiting factor on its performance is the height of the binary tree recall from the vocabulary section that the height of tree is the number of edges between the root and the deepest leaf node the height is the limiting factor because when we are searching for the appropriate place to insert node into the treewe will need to do at most one comparison at each level of the tree what is the height of binary tree likely to bethe answer to this question depends on how trees and tree algorithms
12,716
figure skewed binary search tree would give poor performance the keys are added to the tree if the keys are added in random orderthe height of the tree is going to be around log where is the number of nodes in the tree this is because if the keys are randomly distributedabout half of them will be less than the root and half will be greater than the root remember that in binary tree there is one node at the roottwo nodes in the next leveland four at the next the number of nodes at any particular level is where is the depth of the level the total number of nodes in perfectly balanced binary tree is where represents the height of the tree perfectly balanced tree has the same number of nodes in the left subtree as the right subtree in balanced binary treethe worst-case performance of put is (log )where is the number of nodes in the tree notice that this is the inverse relationship to the calculation in the previous paragraph so log gives us the height of the treeand represents the maximum number of comparisons that put will need to do as it searches for the proper place to insert new node unfortunately it is possible to construct search tree that has height simply by inserting the keys in sorted orderan example of such tree is shown in figure in this case the performance of the put method is (nnow that you understand that the performance of the put method is limited by the height of the treeyou can probably guess that other methodsgetinand delare limited as well since get searches the tree to find the keyin the worst case the tree is searched all the way to the bottom and no key is found at first glance del might seem more complicatedsince it may need to search for the successor before the deletion operation can complete but remember that the worst-case scenario to find the successor is also just the height of the tree which means that you would simply double the work since doubling is constant factor it does not change worst case analysis of (nfor an unbalanced tree summary in this we have looked at the tree data structure the tree data structure enables us to write many interesting algorithms in this we have looked at algorithms that use trees to do the following summary
12,717
the design and analysis of efficient data structures has long been recognized as vital subject in computing and is part of the core curriculum of computer science and computer engineering undergraduate degrees data structures and algorithms in python provides an introduction to data structures and algorithmsincluding their designanalysisand implementation this book is designed for use in beginninglevel data structures courseor in an intermediate-level introduction to algorithms course we discuss its use for such courses in more detail later in this preface to promote the development of robust and reusable softwarewe have tried to take consistent object-oriented viewpoint throughout this text one of the main ideas of the object-oriented approach is that data should be presented as being encapsulated with the methods that access and modify them that israther than simply viewing data as collection of bytes and addresseswe think of data objects as instances of an abstract data type (adt)which includes repertoire of methods for performing operations on data objects of this type we then emphasize that there may be several different implementation strategies for particular adtand explore the relative pros and cons of these choices we provide complete python implementations for almost all data structures and algorithms discussedand we introduce important object-oriented design patterns as means to organize those implementations into reusable components desired outcomes for readers of our book include thatthey have knowledge of the most common abstractions for data collections ( stacksqueuesliststreesmapsthey understand algorithmic strategies for producing efficient realizations of common data structures they can analyze algorithmic performanceboth theoretically and experimentallyand recognize common trade-offs between competing strategies they can wisely use existing data structures and algorithms found in modern programming language libraries they have experience working with concrete implementations for most foundational data structures and algorithms they can apply data structures and algorithms to solve complex problems in support of the last goalwe present many example applications of data structures throughout the bookincluding the processing of file systemsmatching of tags in structured formats such as htmlsimple cryptographytext frequency analysisautomated geometric layouthuffman codingdna sequence alignmentand search engine indexing
12,718
vi book features this book is based upon the book data structures and algorithms in java by goodrich and tamassiaand the related data structures and algorithms in +by goodrichtamassiaand mount howeverthis book is not simply translation of those other books to python in adapting the material for this bookwe have significantly redesigned the organization and content of the book as followsthe code base has been entirely redesigned to take advantage of the features of pythonsuch as use of generators for iterating elements of collection many algorithms that were presented as pseudo-code in the java and +versions are directly presented as complete python code in generaladts are defined to have consistent interface with python' builtin data types and those in python' collections module provides an in-depth exploration of the dynamic array-based underpinnings of python' built-in listtupleand str classes new appendix serves as an additional reference regarding the functionality of the str class over illustrations have been created or revised new and revised exercises bring the overall total number to online resources this book is accompanied by an extensive set of online resourceswhich can be found at the following web sitewww wiley com/college/goodrich students are encouraged to use this site along with the bookto help with exercises and increase understanding of the subject instructors are likewise welcome to use the site to help planorganizeand present their course materials included on this web site is collection of educational aids that augment the topics of this bookfor both students and instructors because of their added valuesome of these online resources are password protected for all readersand especially for studentswe include the following resourcesall the python source code presented in this book pdf handouts of powerpoint slides (four-per-pageprovided to instructors database of hints to all exercisesindexed by problem number for instructors using this bookwe include the following additional teaching aidssolutions to hundreds of the book' exercises color versions of all figures and illustrations from the book slides in powerpoint and pdf (one-per-pageformat the slides are fully editableso as to allow an instructor using this book full freedom in customizing his or her presentations all the online resources are provided at no extra charge to any instructor adopting this book for his or her course
12,719
vii contents and organization the for this book are organized to provide pedagogical path that starts with the basics of python programming and object-oriented design we then add foundational techniques like algorithm analysis and recursion in the main portion of the bookwe present fundamental data structures and algorithmsconcluding with discussion of memory management (that isthe architectural underpinnings of data structuresspecificallythe for this book are organized as follows python primer object-oriented programming algorithm analysis recursion array-based sequences stacksqueuesand deques linked lists trees priority queues mapshash tablesand skip lists search trees sorting and selection text processing graph algorithms memory management and -trees character strings in python useful mathematical facts more detailed table of contents follows this prefacebeginning on page xi prerequisites we assume that the reader is at least vaguely familiar with high-level programming languagesuch as cc++pythonor javaand that he or she understands the main constructs from such high-level languageincludingvariables and expressions decision structures (such as if-statements and switch-statementsiteration structures (for loops and while loopsfunctions (whether stand-alone or object-oriented methodsfor readers who are familiar with these conceptsbut not with how they are expressed in pythonwe provide primer on the python language in stillthis book is primarily data structures booknot python bookhenceit does not give comprehensive treatment of python
12,720
viii we delay treatment of object-oriented programming in python until this is useful for those new to pythonand for those who may be familiar with pythonyet not with object-oriented programming in terms of mathematical backgroundwe assume the reader is somewhat familiar with topics from high-school mathematics even soin we discuss the seven most-important functions for algorithm analysis in factsections that use something other than one of these seven functions are considered optionaland are indicated with star (we give summary of other useful mathematical factsincluding elementary probabilityin appendix relation to computer science curriculum to assist instructors in designing course in the context of the ieee/acm computing curriculumthe following table describes curricular knowledge units that are covered within this book knowledge unit al/basic analysis al/algorithmic strategies al/fundamental data structures and algorithms al/advanced data structures ar/memory system organization and architecture ds/setsrelations and functions ds/proof techniques ds/basics of counting ds/graphs and trees ds/discrete probability pl/object-oriented programming pl/functional programming sdf/algorithms and design sdf/fundamental programming concepts sdf/fundamental data structures sdf/developmental methods se/software design relevant material and sections sections sections much of sections through sections sections sections appendix much of and sections much of the bookyet especially and sections section sections appendix aand sections sections sections mapping ieee/acm computing curriculum knowledge units to coverage in this book
12,721
ix about the authors michael goodrich received his ph in computer science from purdue university in he is currently chancellor' professor in the department of computer science at university of californiairvine previouslyhe was professor at johns hopkins university he is fulbright scholar and fellow of the american association for the advancement of science (aaas)association for computing machinery (acm)and institute of electrical and electronics engineers (ieeehe is recipient of the ieee computer society technical achievement awardthe acm recognition of service awardand the pond award for excellence in undergraduate teaching roberto tamassia received his ph in electrical and computer engineering from the university of illinois at urbana-champaign in he is the plastech professor of computer science and the chair of the department of computer science at brown university he is also the director of brown' center for geometric computing his research interests include information securitycryptographyanalysisdesignand implementation of algorithmsgraph drawing and computational geometry he is fellow of the american association for the advancement of science (aaas)association for computing machinery (acmand institute for electrical and electronic engineers (ieeehe is also recipient of the technical achievement award from the ieee computer society michael goldwasser received his ph in computer science from stanford university in he is currently professor in the department of mathematics and computer science at saint louis university and the director of their computer science program previouslyhe was faculty member in the department of computer science at loyola university chicago his research interests focus on the design and implementation of algorithmshaving published work involving approximation algorithmsonline computationcomputational biologyand computational geometry he is also active in the computer science education community additional books by these authors goodrich and tamassiadata structures and algorithms in javawiley goodrichr tamassiaand mountdata structures and algorithms in ++wiley goodrich and tamassiaalgorithm designfoundationsanalysisand internet exampleswiley goodrich and tamassiaintroduction to computer securityaddisonwesley goldwasser and letscherobject-oriented programming in pythonprentice hall
12,722
acknowledgments we have depended greatly upon the contributions of many individuals as part of the development of this book we begin by acknowledging the wonderful team at wiley we are grateful to our editorbeth golubfor her enthusiastic support of this projectfrom beginning to end the efforts of elizabeth mills and katherine willis were critical in keeping the project movingfrom its early stages as an initial proposalthrough the extensive peer review process we greatly appreciate the attention to detail demonstrated by julie kennedythe copyeditor for this book finallymany thanks are due to joyce poh for managing the final months of the production process we are truly indebted to the outside reviewers and readers for their copious commentsemailsand constructive criticismwhich were extremely useful in writing this edition we therefore thank the following reviewers for their comments and suggestionsclaude anderson (rose hulman institute of technology)alistair campbell (hamilton college)barry cohen (new jersey institute of technology)robert franks (central college)andrew harrington (loyola university chicago)dave musicant (carleton college)and victor norman (calvin collegewe wish to particularly acknowledge claude for going above and beyond the call of dutyproviding us with an enumeration of detailed corrections or suggestions we thank david mountof university of marylandfor graciously sharing the wisdom gained from his experience with the +version of this text we are grateful to erin chambers and david letscherof saint louis universityfor their intangible contributions during many hallway conversations about the teaching of data structuresand to david for comments on early versions of the python code base for this book we thank david zampinoa student at loyola university chicagofor his feedback while using draft of this book during an independent study courseand to andrew harrington for supervising david' studies we also wish to reiterate our thanks to the many research collaborators and teaching assistants whose feedback shaped the previous java and +versions of this material the benefits of those contributions carry forward to this book finallywe would like to warmly thank susan goldwasserisabel cruzkaren goodrichgiuseppe di battistafranco preparataioannis tollisand our parents for providing adviceencouragementand support at various stages of the preparation of this bookand calista and maya goldwasser for offering their advice regarding the artistic merits of many illustrations more importantlywe thank all of these people for reminding us that there are things in life beyond writing books michael goodrich roberto tamassia michael goldwasser
12,723
preface python primer python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops functions information passing python' built-in functions simple input and output console input and output files exception handling raising an exception catching an exception iterators and generators additional python conveniences conditional expressions comprehension syntax packing and unpacking of sequences scopes and namespaces modules and the import statement existing modules exercises xi
12,724
contents object-oriented programming goalsprinciplesand patterns object-oriented design goals object-oriented design principles design patterns software development design pseudo-code coding style and documentation testing and debugging class definitions examplecreditcard class operator overloading and python' special methods examplemultidimensional vector class iterators examplerange class inheritance extending the creditcard class hierarchy of numeric progressions abstract base classes namespaces and object-orientation instance and class namespaces name resolution and dynamic dispatch shallow and deep copying exercises algorithm analysis experimental studies moving beyond experimental analysis the seven functions used in this book comparing growth rates asymptotic analysis the "big-ohnotation comparative analysis examples of algorithm analysis simple justification techniques by example the "contraattack induction and loop invariants exercises
12,725
xiii recursion illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms eliminating tail recursion exercises array-based sequences python' sequence types low-level arrays referential arrays compact arrays in python dynamic arrays and amortization implementing dynamic array amortized analysis of dynamic arrays python' list class efficiency of python' sequence types python' list and tuple classes python' string class using array-based sequences storing high scores for game sorting sequence simple cryptography multidimensional data sets exercises stacksqueuesand deques stacks the stack abstract data type simple array-based stack implementation reversing data using stack matching parentheses and html tags
12,726
contents queues the queue abstract data type array-based queue implementation double-ended queues the deque abstract data type implementing deque with circular array deques in the python collections module exercises linked lists singly linked lists implementing stack with singly linked list implementing queue with singly linked list circularly linked lists round-robin schedulers implementing queue with circularly linked list doubly linked lists basic implementation of doubly linked list implementing deque with doubly linked list the positional list adt the positional list abstract data type doubly linked list implementation sorting positional list case studymaintaining access frequencies using sorted list using list with the move-to-front heuristic link-based vs array-based sequences exercises trees general trees tree definitions and properties the tree abstract data type computing depth and height binary trees the binary tree abstract data type properties of binary trees implementing trees linked structure for binary trees array-based representation of binary tree linked structure for general trees tree traversal algorithms
12,727
xv preorder and postorder traversals of general trees breadth-first tree traversal inorder traversal of binary tree implementing tree traversals in python applications of tree traversals euler tours and the template method pattern case studyan expression tree exercises priority queues the priority queue abstract data type priorities the priority queue adt implementing priority queue the composition design pattern implementation with an unsorted list implementation with sorted list heaps the heap data structure implementing priority queue with heap array-based representation of complete binary tree python heap implementation analysis of heap-based priority queue bottom-up heap construction python' heapq module sorting with priority queue selection-sort and insertion-sort heap-sort adaptable priority queues locators implementing an adaptable priority queue exercises mapshash tablesand skip lists maps and dictionaries the map adt applicationcounting word frequencies python' mutablemapping abstract base class our mapbase class simple unsorted map implementation hash tables hash functions
12,728
contents collision-handling schemes load factorsrehashingand efficiency python hash table implementation sorted maps sorted search tables two applications of sorted maps skip lists search and update operations in skip list probabilistic analysis of skip lists setsmultisetsand multimaps the set adt python' mutableset abstract base class implementing setsmultisetsand multimaps exercises search trees binary search trees navigating binary search tree searches insertions and deletions python implementation performance of binary search tree balanced search trees python framework for balancing search trees avl trees update operations python implementation splay trees splaying when to splay python implementation amortized analysis of splaying ( , trees multiway search trees ( , )-tree operations red-black trees red-black tree operations python implementation exercises
12,729
xvii sorting and selection why study sorting algorithms merge-sort divide-and-conquer array-based implementation of merge-sort the running time of merge-sort merge-sort and recurrence equations alternative implementations of merge-sort quick-sort randomized quick-sort additional optimizations for quick-sort studying sorting through an algorithmic lens lower bound for sorting linear-time sortingbucket-sort and radix-sort comparing sorting algorithms python' built-in sorting functions sorting according to key function selection prune-and-search randomized quick-select analyzing randomized quick-select exercises text processing abundance of digitized text notations for strings and the python str class pattern-matching algorithms brute force the boyer-moore algorithm the knuth-morris-pratt algorithm dynamic programming matrix chain-product dna and text sequence alignment text compression and the greedy method the huffman coding algorithm the greedy method tries standard tries compressed tries suffix tries search engine indexing
12,730
contents exercises graph algorithms graphs the graph adt data structures for graphs edge list structure adjacency list structure adjacency map structure adjacency matrix structure python implementation graph traversals depth-first search dfs implementation and extensions breadth-first search transitive closure directed acyclic graphs topological ordering shortest paths weighted graphs dijkstra' algorithm minimum spanning trees prim-jarnik algorithm kruskal' algorithm disjoint partitions and union-find structures exercises memory management and -trees memory management memory allocation garbage collection additional memory used by the python interpreter memory hierarchies and caching memory systems caching strategies external searching and -trees ( ,btrees -trees external-memory sorting multiway merging exercises
12,731
xix character strings in python useful mathematical facts bibliography index
12,732
python primer contents python overview the python interpreter preview of python program objects in python identifiersobjectsand the assignment statement creating and using objects python' built-in classes expressionsoperatorsand precedence compound expressions and operator precedence control flow conditionals loops functions information passing python' built-in functions simple input and output console input and output files exception handling raising an exception catching an exception iterators and generators additional python conveniences conditional expressions comprehension syntax packing and unpacking of sequences scopes and namespaces modules and the import statement existing modules exercises
12,733
python overview building data structures and algorithms requires that we communicate detailed instructions to computer an excellent way to perform such communications is using high-level computer languagesuch as python the python programming language was originally developed by guido van rossum in the early sand has since become prominently used language in industry and education the second major version of the languagepython was released in and the third major versionpython released in we note that there are significant incompatibilities between python and python this book is based on python (more specificallypython or laterthe latest version of the language is freely available at www python orgalong with documentation and tutorials in this we provide an overview of the python programming languageand we continue this discussion in the next focusing on object-oriented principles we assume that readers of this book have prior programming experiencealthough not necessarily using python this book does not provide complete description of the python language (there are numerous language references for that purpose)but it does introduce all aspects of the language that are used in code fragments later in this book the python interpreter python is formally an interpreted language commands are executed through piece of software known as the python interpreter the interpreter receives commandevaluates that commandand reports the result of the command while the interpreter can be used interactively (especially when debugging) programmer typically defines series of commands in advance and saves those commands in plain text file known as source code or script for pythonsource code is conventionally stored in file named with the py suffix ( demo pyon most operating systemsthe python interpreter can be started by typing python from the command line by defaultthe interpreter starts in interactive mode with clean workspace commands from predefined script saved in file ( demo pyare executed by invoking the interpreter with the filename as an argument ( python demo py)or using an additional - flag in order to execute script and then enter interactive mode ( python - demo pymany integrated development environments (idesprovide richer software development platforms for pythonincluding one named idle that is included with the standard python distribution idle provides an embedded text-editor with support for displaying and editing python codeand basic debuggerallowing step-by-step execution of program while examining key variable values
12,734
preview of python program as simple introductioncode fragment presents python program that computes the grade-point average (gpafor student based on letter grades that are entered by user many of the techniques demonstrated in this example will be discussed in the remainder of this at this pointwe draw attention to few high-level issuesfor readers who are new to python as programming language python' syntax relies heavily on the use of whitespace individual statements are typically concluded with newline characteralthough command can extend to another lineeither with concluding backslash character (\)or if an opening delimiter has not yet been closedsuch as the character in defining value map whitespace is also key in delimiting the bodies of control structures in python specificallya block of code is indented to designate it as the body of control structureand nested control structures use increasing amounts of indentation in code fragment the body of the while loop consists of the subsequent linesincluding nested conditional structure comments are annotations provided for human readersyet ignored by the python interpreter the primary syntax for comments in python is based on use of the characterwhich designates the remainder of the line as comment printwelcome to the gpa calculator printplease enter all your letter gradesone per line printenter blank line to designate the end map from letter grade to point value points : : : : : : : : : : : : num courses total points done false while not donegrade inputread line from user empty line was entered if grade =done true elif grade not in pointsunrecognized grade entered print("unknown grade { being ignoredformat(grade)elsenum courses + total points +points[gradeavoid division by zero if num courses printyour gpa is { format(total points num courses)code fragment python program that computes grade-point average (gpa
12,735
objects in python python is an object-oriented language and classes form the basis for all data types in this sectionwe describe key aspects of python' object modeland we introduce python' built-in classessuch as the int class for integersthe float class for floating-point valuesand the str class for character strings more thorough presentation of object-orientation is the focus of identifiersobjectsand the assignment statement the most important of all python commands is an assignment statementsuch as temperature this command establishes temperature as an identifier (also known as name)and then associates it with the object expressed on the right-hand side of the equal signin this case floating-point object with value we portray the outcome of this assignment in figure float temperature figure the identifier temperature references an instance of the float class having value identifiers identifiers in python are case-sensitiveso temperature and temperature are distinct names identifiers can be composed of almost any combination of lettersnumeralsand underscore characters (or more general unicode charactersthe primary restrictions are that an identifier cannot begin with numeral (thus lives is an illegal name)and that there are specially reserved words that cannot be used as identifiersas shown in table false none true and as assert break class continue def del elif reserved words else from in except global is finally if lambda for import nonlocal not or pass raise return try while with yield table listing of the reserved words in python these names cannot be used as identifiers
12,736
for readers familiar with other programming languagesthe semantics of python identifier is most similar to reference variable in java or pointer variable in +each identifier is implicitly associated with the memory address of the object to which it refers python identifier may be assigned to special object named noneserving similar purpose to null reference in java or +unlike java and ++python is dynamically typed languageas there is no advance declaration associating an identifier with particular data type an identifier can be associated with any type of objectand it can later be reassigned to another object of the same (or differenttype although an identifier has no declared typethe object to which it refers has definite type in our first examplethe characters are recognized as floating-point literaland thus the identifier temperature is associated with an instance of the float class having that value programmer can establish an alias by assigning second identifier to an existing object continuing with our earlier examplefigure portrays the result of subsequent assignmentoriginal temperature float temperature original figure identifiers temperature and original are aliases for the same object once an alias has been establishedeither name can be used to access the underlying object if that object supports behaviors that affect its statechanges enacted through one alias will be apparent when using the other alias (because they refer to the same objecthoweverif one of the names is reassigned to new value using subsequent assignment statementthat does not affect the aliased objectrather it breaks the alias continuing with our concrete examplewe consider the commandtemperature temperature the execution of this command begins with the evaluation of the expression on the right-hand side of the operator that expressiontemperature is evaluated based on the existing binding of the name temperatureand so the result has value that is that result is stored as new floating-point instanceand only then is the name on the left-hand side of the assignment statementtemperature(re)assigned to the result the subsequent configuration is diagrammed in figure of particular notethis last command had no effect on the value of the existing float instance that identifier original continues to reference float float temperature original figure the temperature identifier has been assigned to new valuewhile original continues to refer to the previously existing value
12,737
creating and using objects instantiation the process of creating new instance of class is known as instantiation in generalthe syntax for instantiating an object is to invoke the constructor of class for exampleif there were class named widgetwe could create an instance of that class using syntax such as widget)assuming that the constructor does not require any parameters if the constructor does require parameterswe might use syntax such as widget(abcto construct new instance many of python' built-in classes (discussed in section support what is known as literal form for designating new instances for examplethe command temperature results in the creation of new instance of the float classthe term in that expression is literal form we discuss further cases of python literals in the coming section from programmer' perspectiveyet another way to indirectly create new instance of class is to call function that creates and returns such an instance for examplepython has built-in function named sorted (see section that takes sequence of comparable elements as parameter and returns new instance of the list class containing those elements in sorted order calling methods python supports traditional functions (see section that are invoked with syntax such as sorted(data)in which case data is parameter sent to the function python' classes may also define one or more methods (also known as member functions)which are invoked on specific instance of class using the dot ("operator for examplepython' list class has method named sort that can be invoked with syntax such as data sortthis particular method rearranges the contents of the list so that they are sorted the expression to the left of the dot identifies the object upon which the method is invoked oftenthis will be an identifier ( data)but we can use the dot operator to invoke method upon the immediate result of some other operation for exampleif response identifies string instance (we will discuss strings later in this section)the syntax response lowerstartswithy first evaluates the method callresponse lower)which itself returns new string instanceand then the startswithy method is called on that intermediate string when using method of classit is important to understand its behavior some methods return information about the state of an objectbut do not change that state these are known as accessors other methodssuch as the sort method of the list classdo change the state of an object these methods are known as mutators or update methods
12,738
python' built-in classes table provides summary of commonly usedbuilt-in classes in pythonwe take particular note of which classes are mutable and which are immutable class is immutable if each object of that class has fixed value upon instantiation that cannot subsequently be changed for examplethe float class is immutable once an instance has been createdits value cannot be changed (although an identifier referencing that object can be reassigned to different valueclass bool int float list tuple str set frozenset dict description boolean value integer (arbitrary magnitudefloating-point number mutable sequence of objects immutable sequence of objects character string unordered set of distinct objects immutable form of set class associative mapping (aka dictionaryimmutable table commonly used built-in classes for python in this sectionwe provide an introduction to these classesdiscussing their purpose and presenting several means for creating instances of the classes literal forms (such as exist for most of the built-in classesand all of the classes support traditional constructor form that creates instances that are based upon one or more existing values operators supported by these classes are described in section more detailed information about these classes can be found in later as followslists and tuples ()strings and and appendix )sets and dictionaries (the bool class the bool class is used to manipulate logical (booleanvaluesand the only two instances of that class are expressed as the literals true and false the default constructorbool)returns falsebut there is no reason to use that syntax rather than the more direct literal form python allows the creation of boolean value from nonboolean type using the syntax bool(foofor value foo the interpretation depends upon the type of the parameter numbers evaluate to false if zeroand true if nonzero sequences and other container typessuch as strings and listsevaluate to false if empty and true if nonempty an important application of this interpretation is the use of nonboolean value as condition in control structure
12,739
the int class the int and float classes are the primary numeric types in python the int class is designed to represent integer values with arbitrary magnitude unlike java and ++which support different integral types with different precisions ( intshortlong)python automatically chooses the internal representation for an integer based upon the magnitude of its value typical literals for integers include and - in some contextsit is convenient to express an integral value using binaryoctalor hexadecimal that can be done by using prefix of the number and then character to describe the base example of such literals are respectively and the integer constructorint)returns value by default but this constructor can be used to construct an integer value based upon an existing value of another type for exampleif represents floating-point valuethe syntax int(fproduces the truncated value of for exampleboth int( and int( produce the value while int(- produces the value - the constructor can also be used to parse string that is presumed to represent an integral value (such as one entered by userif represents stringthen int(sproduces the integral value that string represents for examplethe expression int produces the integer value if an invalid string is given as parameteras in inthello ) valueerror is raised (see section for discussion of python' exceptionsby defaultthe string must use base if conversion from different base is desiredthat base can be indicated as secondoptionalparameter for examplethe expression int evaluates to the integer the float class the float class is the sole floating-point type in pythonusing fixed-precision representation its precision is more akin to double in java or ++rather than those languagesfloat type we have already discussed typical literal form we note that the floating-point equivalent of an integral number can be expressed directly as technicallythe trailing zero is optionalso some programmers might use the expression to designate this floating-point literal one other form of literal for floating-point values uses scientific notation for examplethe literal represents the mathematical value the constructor form of floatreturns when given parameterthe constructor attempts to return the equivalent floating-point value for examplethe call float( returns the floating-point value if the parameter to the constructor is stringas with float )it attempts to parse that string as floating-point valueraising valueerror as an exception
12,740
sequence typesthe listtupleand str classes the listtupleand str classes are sequence types in pythonrepresenting collection of values in which the order is significant the list class is the most generalrepresenting sequence of arbitrary objects (akin to an "arrayin other languagesthe tuple class is an immutable version of the list classbenefiting from streamlined internal representation the str class is specially designed for representing an immutable sequence of text characters we note that python does not have separate class for charactersthey are just strings with length one the list class list instance stores sequence of objects list is referential structureas it technically stores sequence of references to its elements (see figure elements of list may be arbitrary objects (including the none objectlists are array-based sequences and are zero-indexedthus list of length has elements indexed from to inclusive lists are perhaps the most used container type in python and they will be extremely central to our study of data structures and algorithms they have many valuable behaviorsincluding the ability to dynamically expand and contract their capacities as needed in this we will discuss only the most basic properties of lists we revisit the inner working of all of python' sequence types as the focus of python uses the characters as delimiters for list literalwith itself being an empty list as another examplered green blue is list containing three string instances the contents of list literal need not be expressed as literalsif identifiers and have been establishedthen syntax [abis legitimate the listconstructor produces an empty list by default howeverthe constructor will accept any parameter that is of an iterable type we will discuss iteration further in section but examples of iterable types include all of the standard container types ( stringslisttuplessetsdictionariesfor examplethe syntax listhello produces list of individual charactersh because an existing list is itself iterablethe syntax backup list(datacan be used to construct new list instance referencing the same contents as the original primes figure python' internal representation of list of integersinstantiated as prime [ the implicit indices of the elements are shown below each entry
12,741
the tuple class the tuple class provides an immutable version of sequenceand therefore its instances have an internal representation that may be more streamlined than that of list while python uses the characters to delimit listparentheses delimit tuplewith being an empty tuple there is one important subtlety to express tuple of length one as literala comma must be placed after the elementbut within the parentheses for example( ,is one-element tuple the reason for this requirement is thatwithout the trailing commathe expression ( is viewed as simple parenthesized numeric expression the str class python' str class is specifically designed to efficiently represent an immutable sequence of charactersbased upon the unicode international character set strings have more compact internal representation than the referential lists and tuplesas portrayed in figure figure python stringwhich is an indexed sequence of characters string literals can be enclosed in single quotesas in hello or double quotesas in "hellothis choice is convenientespecially when using another of the quotation characters as an actual character in the sequenceas in "don worryalternativelythe quote delimiter can be designated using backslash as so-called escape characteras in dont worry because the backslash has this purposethe backslash must itself be escaped to occur as natural character of the string literalas in :\\python\for string that would be displayed as :\pythonother commonly escaped characters are \ for newline and \ for tab unicode characters can be includedsuch as \ ac for the string or ""to begin and end string python also supports using the delimiter literal the advantage of such triple-quoted strings is that newline characters can be embedded naturally (rather than escaped as \nthis can greatly improve the readability of longmultiline strings in source code for exampleat the beginning of code fragment rather than use separate print statements for each line of introductory outputwe can use single print statementas followsprint("""welcome to the gpa calculator please enter all your letter gradesone per line enter blank line to designate the end """
12,742
the set and frozenset classes python' set class represents the mathematical notion of setnamely collection of elementswithout duplicatesand without an inherent order to those elements the major advantage of using setas opposed to listis that it has highly optimized method for checking whether specific element is contained in the set this is based on data structure known as hash table (which will be the primary topic of howeverthere are two important restrictions due to the algorithmic underpinnings the first is that the set does not maintain the elements in any particular order the second is that only instances of immutable types can be added to python set thereforeobjects such as integersfloating-point numbersand character strings are eligible to be elements of set it is possible to maintain set of tuplesbut not set of lists or set of setsas lists and sets are mutable the frozenset class is an immutable form of the set typeso it is legal to have set of frozensets python uses curly braces and as delimiters for setfor exampleas { or red green blue the exception to this rule is that does not represent an empty setfor historical reasonsit represents an empty dictionary (see next paragraphinsteadthe constructor syntax setproduces an empty set if an iterable parameter is sent to the constructorthen the set of distinct elements is produced for examplesethello produces the dict class python' dict class represents dictionaryor mappingfrom set of distinct keys to associated values for examplea dictionary might map from unique student id numbersto larger student records (such as the student' nameaddressand course gradespython implements dict using an almost identical approach to that of setbut with storage of the associated values dictionary literal also uses curly bracesand because dictionaries were introduced in python prior to setsthe literal form produces an empty dictionary nonempty dictionary is expressed using comma-separated series of key:value pairs for examplethe dictionary ga irish de german maps ga to irish and de to german the constructor for the dict class accepts an existing mapping as parameterin which case it creates new dictionary with identical associations as the existing one alternativelythe constructor accepts sequence of key-value pairs as parameteras in dict(pairswith pairs [ga irish )de german )
12,743
expressionsoperatorsand precedence in the previous sectionwe demonstrated how names can be used to identify existing objectsand how literals and constructors can be used to create instances of built-in classes existing values can be combined into larger syntactic expressions using variety of special symbols and keywords known as operators the semantics of an operator depends upon the type of its operands for examplewhen and are numbersthe syntax indicates additionwhile if and are stringsthe operator indicates concatenation in this sectionwe describe python' operators in various contexts of the built-in types we continuein section by discussing compound expressionssuch as cwhich rely on the evaluation of two or more operations the order in which the operations of compound expression are evaluated can affect the overall value of the expression for this reasonpython defines specific order of precedence for evaluating operatorsand it allows programmer to override this order by using explicit parentheses to group subexpressions logical operators python supports the following keyword operators for boolean valuesnot unary negation and conditional and or conditional or the and and or operators short-circuitin that they do not evaluate the second operand if the result can be determined based on the value of the first operand this feature is useful when constructing boolean expressions in which we first test that certain condition holds (such as reference not being none)and then test condition that could have otherwise generated an error condition had the prior test not succeeded equality operators python supports the following operators to test two notions of equalityis same identity is not different identity =equivalent !not equivalent the expression is evaluates to trueprecisely when identifiers and are aliases for the same object the expression = tests more general notion of equivalence if identifiers and refer to the same objectthen = should also evaluate to true yet = also evaluates to true when the identifiers refer to
12,744
different objects that happen to have values that are deemed equivalent the precise notion of equivalence depends on the data type for exampletwo strings are considered equivalent if they match character for character two sets are equivalent if they have the same contentsirrespective of order in most programming situationsthe equivalence tests =and !are the appropriate operatorsuse of is and is not should be reserved for situations in which it is necessary to detect true aliasing comparison operators data types may define natural order via the following operatorsless than <less than or equal to greater than >greater than or equal to these operators have expected behavior for numeric typesand are defined lexicographicallyand case-sensitivelyfor strings an exception is raised if operands have incomparable typesas with hello arithmetic operators python supports the following arithmetic operatorsaddition subtraction multiplication true division /integer division the modulo operator the use of additionsubtractionand multiplication is straightforwardnoting that if both operands have type intthen the result is an int as wellif one or both operands have type floatthe result will be float python takes more care in its treatment of division we first consider the case in which both operands have type intfor examplethe quantity divided by in mathematical notation in pythonthe operator designates true divisionreturning the floating-point result of the computation thus results in the float value python supports the pair of operators /and to perform the integral calculationswith expression / evaluating to int value (the mathematical floor of the quotient)and expression evaluating to int value the remainder of the integer division we note that languages such as cc++and java do not support the /operatorinsteadthe operator returns the truncated quotient when both operands have integral typeand the result of true division when at least one operand has floating-point type
12,745
python carefully extends the semantics of /and to cases where one or both operands are negative for the sake of notationlet us assume that variables and that and represent respectively the dividend and divisor of quotient / and python guarantees that will equal we already saw an example of this identity with positive operandsas when the divisor is positivepython further guarantees that < as consequencewe find that - / evaluates to - and - evaluates to as (- - when the divisor is negativepython guarantees that < as an example /- is - and - is - satisfying the identity (- (- (- the conventions for the /and operators are even extended to floatingpoint operandswith the expression / being the integral floor of the quotientand being the "remainderto ensure that equals for example / evaluates to and evaluates to as bitwise operators python provides the following bitwise operators for integersbitwise complement (prefix unary operatorbitwise and bitwise or bitwise exclusive-or <shift bits leftfilling in with zeros >shift bits rightfilling in with sign bit sequence operators each of python' built-in sequence types (strtupleand listsupport the following operator syntaxess[jelement at index [start:stopslice including indices [start,stops[start:stop:stepslice including indices startstart stepstart stepup to but not equalling or stop + concatenation of sequences shorthand for ( timesk val in containment check val not in non-containment check python relies on zero-indexing of sequencesthus sequence of length has elements indexed from to inclusive python also supports the use of negative indiceswhich denote distance from the end of the sequenceindex - denotes the last elementindex - the second to lastand so on python uses slicing
12,746
notation to describe subsequences of sequence slices are described as half-open intervalswith start index that is includedand stop index that is excluded for examplethe syntax data[ : denotes subsequence including the five indices an optional "stepvaluepossibly negativecan be indicated as third parameter of the slice if start index or stop index is omitted in the slicing notationit is presumed to designate the respective extreme of the original sequence because lists are mutablethe syntax [jval can be used to replace an element at given index lists also support syntaxdel [ ]that removes the designated element from the list slice notation can also be used to replace or delete sublist the notation val in can be used for any of the sequences to see if there is an element equivalent to val in the sequence for stringsthis syntax can be used to check for single character or for larger substringas with amp in example all sequences define comparison operations based on lexicographic orderperforming an element by element comparison until the first difference is found for example[ [ because of the entries at index thereforethe following operations are supported by sequence typess = equivalent (element by elements ! not equivalent lexicographically less than < lexicographically less than or equal to lexicographically greater than > lexicographically greater than or equal to operators for sets and dictionaries sets and frozensets support the following operatorskey in containment check key not in non-containment check = is equivalent to ! is not equivalent to < is subset of is proper subset of > is superset of is proper superset of the union of and the intersection of and the set of elements in but not the set of elements in precisely one of or note well that sets do not guarantee particular order of their elementsso the comparison operatorssuch as <are not lexicographicratherthey are based on the mathematical notion of subset as resultthe comparison operators define
12,747
partial orderbut not total orderas disjoint sets are neither "less than,"equal to,or "greater thaneach other sets also support many fundamental behaviors through named methods ( addremove)we will explore their functionality more fully in dictionarieslike setsdo not maintain well-defined order on their elements furthermorethe concept of subset is not typically meaningful for dictionariesso the dict class does not support operators such as dictionaries support the notion of equivalencewith = if the two dictionaries contain the same set of keyvalue pairs the most widely used behavior of dictionaries is accessing value associated with particular key with the indexing syntaxd[kthe supported operators are as followsd[keyd[keyvalue del [keykey in key not in = ! value associated with given key set (or resetthe value associated with given key remove key and its associated value from dictionary containment check non-containment check is equivalent to is not equivalent to dictionaries also support many useful behaviors through named methodswhich we explore more fully in extended assignment operators python supports an extended assignment operator for most binary operatorsfor exampleallowing syntax such as count + by defaultthis is shorthand for the more verbose count count for an immutable typesuch as number or stringone should not presume that this syntax changes the value of the existing objectbut instead that it will reassign the identifier to newly constructed value (see discussion of figure howeverit is possible for type to redefine such semantics to mutate the objectas the list class does for the +operator alpha [ beta alpha beta +[ beta beta [ print(alphaan alias for alpha extends the original list with two more elements reassigns beta to new list [ will be [ this example demonstrates the subtle difference between the list semantics for the syntax beta +foo versus beta beta foo
12,748
compound expressions and operator precedence programming languages must have clear rules for the order in which compound expressionssuch as are evaluated the formal order of precedence for operators in python is given in table operators in category with higher precedence will be evaluated before those with lower precedenceunless the expression is otherwise parenthesized thereforewe see that python gives precedence to multiplication over additionand therefore evaluates the expression as ( )with value but the parenthesized expression ( evaluates to value operators within category are typically evaluated from left to rightthus has value exceptions to this rule include that unary operators and exponentiation are evaluated from right to left python allows chained assignmentsuch as to assign multiple identifiers to the rightmost value python also allows the chaining of comparison operators for examplethe expression < < is evaluated as the compound ( < yand ( < )but without computing the intermediate value twice operator precedence type symbols member access expr member function/method calls exprcontainer subscripts/slices exprexponentiation unary operators +expr-expr~expr multiplicationdivision ///additionsubtraction +bitwise shifting bitwise-and bitwise-xor bitwise-or comparisons isis not==!=>containment innot in logical-not not expr logical-and and logical-or or conditional val if cond else val assignments =+=-==etc table operator precedence in pythonwith categories ordered from highest precedence to lowest precedence when statedwe use expr to denote literalidentifieror result of previously evaluated expression all operators without explicit mention of expr are binary operatorswith syntax expr operator expr
12,749
control flow in this sectionwe review python' most fundamental control structuresconditional statements and loops common to all control structures is the syntax used in python for defining blocks of code the colon character is used to delimit the beginning of block of code that acts as body for control structure if the body can be stated as single executable statementit can technically placed on the same lineto the right of the colon howevera body is more typically typeset as an indented block starting on the line following the colon python relies on the indentation level to designate the extent of that block of codeor any nested blocks of code within the same principles will be applied when designating the body of function (see section )and the body of class (see section conditionals conditional constructs (also known as if statementsprovide way to execute chosen block of code based on the run-time evaluation of one or more boolean expressions in pythonthe most general form of conditional is written as followsif first conditionfirst body elif second conditionsecond body elif third conditionthird body elsefourth body each condition is boolean expressionand each body contains one or more commands that are to be executed conditionally if the first condition succeedsthe first body will be executedno other conditions or bodies are evaluated in that case if the first condition failsthen the process continues in similar manner with the evaluation of the second condition the execution of this overall construct will cause precisely one of the bodies to be executed there may be any number of elif clauses (including zero)and the final else clause is optional as described on page nonboolean types may be evaluated as booleans with intuitive meanings for exampleif response is string that was entered by userand we want to condition behavior on this being nonempty stringwe may write if responseas shorthand for the equivalentif response !
12,750
as simple examplea robot controller might have the following logicif door is closedopen dooradvancenotice that the final commandadvance)is not indented and therefore not part of the conditional body it will be executed unconditionally (although after opening closed doorwe may nest one control structure within anotherrelying on indentation to make clear the extent of the various bodies revisiting our robot examplehere is more complex control that accounts for unlocking closed door if door is closedif door is lockedunlock dooropen dooradvancethe logic expressed by this example can be diagrammed as traditional flowchartas portrayed in figure false door is closed true false door is locked true unlock dooropen dooradvancefigure flowchart describing the logic of nested conditional statements
12,751
loops python offers two distinct looping constructs while loop allows general repetition based upon the repeated testing of boolean condition for loop provides convenient iteration of values from defined series (such as characters of stringelements of listor numbers within given rangewe discuss both forms in this section while loops the syntax for while loop in python is as followswhile conditionbody as with an if statementcondition can be an arbitrary boolean expressionand body can be an arbitrary block of code (including nested control structuresthe execution of while loop begins with test of the boolean condition if that condition evaluates to truethe body of the loop is performed after each execution of the bodythe loop condition is retestedand if it evaluates to trueanother iteration of the body is performed when the conditional test evaluates to false (assuming it ever does)the loop is exited and the flow of control continues just beyond the body of the loop as an examplehere is loop that advances an index through sequence of characters until finding an entry with value or reaching the end of the sequence = while len(dataand data[ ! + the len functionwhich we will introduce in section returns the length of sequence such as list or string the correctness of this loop relies on the shortcircuiting behavior of the and operatoras described on page we intentionally test len(datato ensure that is valid indexprior to accessing element data[jhad we written that compound condition with the opposite orderthe evaluation of data[jwould eventually raise an indexerror when is not found (see section for discussion of exceptions as writtenwhen this loop terminatesvariable ' value will be the index of the leftmost occurrence of if foundor otherwise the length of the sequence (which is recognizable as an invalid index to indicate failure of the searchit is worth noting that this code behaves correctlyeven in the special case when the list is emptyas the condition len(datawill initially fail and the body of the loop will never be executed
12,752
for loops python' for-loop syntax is more convenient alternative to while loop when iterating through series of elements the for-loop syntax can be used on any type of iterable structuresuch as listtuple strsetdictor file (we will discuss iterators more formally in section its general syntax appears as follows for element in iterablebody body may refer to element as an identifier for readers familiar with javathe semantics of python' for loop is similar to the "for eachloop style introduced in java as an instructive example of such loopwe consider the task of computing the sum of list of numbers (admittedlypython has built-in functionsumfor this purpose we perform the calculation with for loop as followsassuming that data identifies the listtotal for val in datatotal +val note use of the loop variableval the loop body executes once for each element of the data sequencewith the identifiervalfrom the for-loop syntax assigned at the beginning of each pass to respective element it is worth noting that val is treated as standard identifier if the element of the original data happens to be mutablethe val identifier can be used to invoke its methods but reassignment of identifier val to new value has no affect on the original datanor on the next iteration of the loop as second classic examplewe consider the task of finding the maximum value in list of elements (againadmitting that python' built-in max function already provides this supportif we can assume that the listdatahas at least one elementwe could implement this task as followsbiggest data[ for val in dataif val biggestbiggest val as we assume nonempty list although we could accomplish both of the above tasks with while loopthe for-loop syntax had an advantage of simplicityas there is no need to manage an explicit index into the list nor to author boolean loop condition furthermorewe can use for loop in cases for which while loop does not applysuch as when iterating through collectionsuch as setthat does not support any direct form of indexing
12,753
index-based for loops the simplicity of standard for loop over the elements of list is wonderfulhoweverone limitation of that form is that we do not know where an element resides within the sequence in some applicationswe need knowledge of the index of an element within the sequence for examplesuppose that we want to know where the maximum element in list resides rather than directly looping over the elements of the list in that casewe prefer to loop over all possible indices of the list for this purposepython provides built-in class named range that generates integer sequences (we will discuss generators in section in simplest formthe syntax range(ngenerates the series of values from to convenientlythese are precisely the series of valid indices into sequence of length thereforea standard python idiom for looping through the series of indices of data sequence uses syntaxfor in range(len(data))in this caseidentifier is not an element of the data--it is an integer but the expression data[jcan be used to retrieve the respective element for examplewe can find the index of the maximum element of list as followsbig index for in range(len(data))if data[jdata[big index]big index break and continue statements python supports break statement that immediately terminate while or for loop when executed within its body more formallyif applied within nested control structuresit causes the termination of the most immediately enclosing loop as typical examplehere is code that determines whether target value occurs in data setfound false for item in dataif item =targetfound true break python also supports continue statement that causes the current iteration of loop body to stopbut with subsequent passes of the loop proceeding as expected we recommend that the break and continue statements be used sparingly yetthere are situations in which these commands can be effectively used to avoid introducing overly complex logical conditions
12,754
functions in this sectionwe explore the creation of and use of functions in python as we did in section we draw distinction between functions and methods we use the general term function to describe traditionalstateless function that is invoked without the context of particular class or an instance of that classsuch as sorted(datawe use the more specific term method to describe member function that is invoked upon specific object using an object-oriented message passing syntaxsuch as data sortin this sectionwe only consider pure functionsmethods will be explored with more general object-oriented principles in we begin with an example to demonstrate the syntax for defining functions in python the following function counts the number of occurrences of given target value within any form of iterable data set def count(datatarget) = for item in dataif item =targetn + return found match the first linebeginning with the keyword defserves as the function' signature this establishes new identifier as the name of the function (countin this example)and it establishes the number of parameters that it expectsas well as names identifying those parameters (data and targetin this exampleunlike java and ++python is dynamically typed languageand therefore python signature does not designate the types of those parametersnor the type (if anyof return value those expectations should be stated in the function' documentation (see section and can be enforced within the body of the functionbut misuse of function will only be detected at run-time the remainder of the function definition is known as the body of the function as is the case with control structures in pythonthe body of function is typically expressed as an indented block of code each time function is calledpython creates dedicated activation record that stores information relevant to the current call this activation record includes what is known as namespace (see section to manage all identifiers that have local scope within the current call the namespace includes the function' parameters and any other identifiers that are defined locally within the body of the function an identifier in the local scope of the function caller has no relation to any identifier with the same name in the caller' scope (although identifiers in different scopes may be aliases to the same objectin our first examplethe identifier has scope that is local to the function callas does the identifier itemwhich is established as the loop variable
12,755
return statement return statement is used within the body of function to indicate that the function should immediately cease executionand that an expressed value should be returned to the caller if return statement is executed without an explicit argumentthe none value is automatically returned likewisenone will be returned if the flow of control ever reaches the end of function body without having executed return statement oftena return statement will be the final command within the body of the functionas was the case in our earlier example of count function howeverthere can be multiple return statements in the same functionwith conditional logic controlling which such command is executedif any as further exampleconsider the following function that tests if value exists in sequence def contains(datatarget)for item in targetif item =targetreturn true return false found match if the conditional within the loop body is ever satisfiedthe return true statement is executed and the function immediately endswith true designating that the target value was found converselyif the for loop reaches its conclusion without ever finding the matchthe final return false statement will be executed information passing to be successful programmerone must have clear understanding of the mechanism in which programming language passes information to and from function in the context of function signaturethe identifiers used to describe the expected parameters are known as formal parametersand the objects sent by the caller when invoking the function are the actual parameters parameter passing in python follows the semantics of the standard assignment statement when function is invokedeach identifier that serves as formal parameter is assignedin the function' local scopeto the respective actual parameter that is provided by the caller of the function for exampleconsider the following call to our count function from page prizes count(gradesa just before the function body is executedthe actual parametersgrades and are implicitly assigned to the formal parametersdata and targetas followsdata grades target
12,756
these assignment statements establish identifier data as an alias for grades and target as name for the string literal (see figure grades data target list str figure portrayal of parameter passing in pythonfor the function call count(gradesa identifiers data and target are formal parameters defined within the local scope of the count function the communication of return value from the function back to the caller is similarly implemented as an assignment thereforewith our sample invocation of prizes count(gradesa )the identifier prizes in the caller' scope is assigned to the object that is identified as in the return statement within our function body an advantage to python' mechanism for passing information to and from function is that objects are not copied this ensures that the invocation of function is efficienteven in case where parameter or return value is complex object mutable parameters python' parameter passing model has additional implications when parameter is mutable object because the formal parameter is an alias for the actual parameterthe body of the function may interact with the object in ways that change its state considering again our sample invocation of the count functionif the body of the function executes the command data appendf )the new entry is added to the end of the list identified as data within the functionwhich is one and the same as the list known to the caller as grades as an asidewe note that reassigning new value to formal parameter with function bodysuch as by setting data ]does not alter the actual parametersuch reassignment simply breaks the alias our hypothetical example of count method that appends new element to list lacks common sense there is no reason to expect such behaviorand it would be quite poor design to have such an unexpected effect on the parameter there arehowevermany legitimate cases in which function may be designed (and clearly documentedto modify the state of parameter as concrete examplewe present the following implementation of method named scale that' primary purpose is to multiply all entries of numeric data set by given factor def scale(datafactor)for in range(len(data))data[jfactor
12,757
default parameter values python provides means for functions to support more than one possible calling signature such function is said to be polymorphic (which is greek for "many forms"most notablyfunctions can declare one or more default values for parametersthereby allowing the caller to invoke function with varying numbers of actual parameters as an artificial exampleif function is declared with signature def foo(ab= = )there are three parametersthe last two of which offer default values caller is welcome to send three actual parametersas in foo( )in which case the default values are not used ifon the other handthe caller only sends one parameterfoo( )the function will execute with parameters values = = = if caller sends two parametersthey are assumed to be the first twowith the third being the default thusfoo( executes with = = = howeverit is illegal to define function with signature such as bar(ab= cwith having default valueyet not the subsequent cif default parameter value is present for one parameterit must be present for all further parameters as more motivating example for the use of default parameterwe revisit the task of computing student' gpa (see code fragment rather than assume direct input and output with the consolewe prefer to design function that computes and returns gpa our original implementation uses fixed mapping from each letter grade (such as -to corresponding point value (such as while that point system is somewhat commonit may not agree with the system used by all schools (for examplesome may assign an agrade value higher than thereforewe design compute gpa functiongiven in code fragment which allows the caller to specify custom mapping from grades to valueswhile offering the standard point system as default def compute gpa(gradespoints= : : : : : : : : : : : : })num courses total points for in gradesif in pointsa recognizable grade num courses + total points +points[greturn total points num courses code fragment function that computes student' gpa with point value system that can be customized as an optional parameter
12,758
as an additional example of an interesting polymorphic functionwe consider python' support for range (technicallythis is constructor for the range classbut for the sake of this discussionwe can treat it as pure function three calling syntaxes are supported the one-parameter formrange( )generates sequence of integers from up to but not including two-parameter formrange(start,stopgenerates integers from start up tobut not includingstop three-parameter formrange(startstopstep)generates similar range as range(startstop)but with increments of size step rather than this combination of forms seems to violate the rules for default parameters in particularwhen single parameter is sentas in range( )it serves as the stop value (which is the second parameter)the value of start is effectively in that case howeverthis effect can be achieved with some sleight of handas followsdef range(startstop=nonestep= )if stop is nonestop start start from technical perspectivewhen range(nis invokedthe actual parameter will be assigned to formal parameter start within the bodyif only one parameter is receivedthe start and stop values are reassigned to provide the desired semantics keyword parameters the traditional mechanism for matching the actual parameters sent by callerto the formal parameters declared by the function signature is based on the concept of positional arguments for examplewith signature foo( = = = )parameters sent by the caller are matchedin the given orderto the formal parameters an invocation of foo( indicates that = while and are assigned their default values python supports an alternate mechanism for sending parameter to function known as keyword argument keyword argument is specified by explicitly assigning an actual parameter to formal parameter by name for examplewith the above definition of function fooa call foo( = will invoke the function with parameters = = = function' author can require that certain parameters be sent only through the keyword-argument syntax we never place such restriction in our own function definitionsbut we will see several important uses of keyword-only parameters in python' standard libraries as an examplethe built-in max function accepts keyword parametercoincidentally named keythat can be used to vary the notion of "maximumthat is used
12,759
by defaultmax operates based upon the natural order of elements according to the operator for that type but the maximum can be computed by comparing some other aspect of the elements this is done by providing an auxiliary function that converts natural element to some other value for the sake of comparison for exampleif we are interested in finding numeric value with magnitude that is maximal ( considering - to be larger than + )we can use the calling syntax max(abkey=absin this casethe built-in abs function is itself sent as the value associated with the keyword parameter key (functions are first-class objects in pythonsee section when max is called in this wayit will compare abs(ato abs( )rather than to the motivation for the keyword syntax as an alternate to positional arguments is important in the case of max this function is polymorphic in the number of argumentsallowing call such as max( , , , )thereforeit is not possible to designate key function as traditional positional element sorting functions in python also support similar key parameter for indicating nonstandard order (we explore this further in section and in section when discussing sorting algorithmspython' built-in functions table provides an overview of common functions that are automatically available in pythonincluding the previously discussed absmaxand range when choosing names for the parameterswe use identifiers xyz for arbitrary numeric typesk for an integerand aband for arbitrary comparable types we use the identifieriterableto represent an instance of any iterable type ( strlisttuplesetdict)we will discuss iterators and iterable data types in section sequence represents more narrow category of indexable classesincluding strlistand tuplebut neither set nor dict most of the entries in table can be categorized according to their functionality as followsinput/outputprintinputand open will be more fully explained in section character encodingord and chr relate characters and their integer code points for exampleorda is and chr( is mathematicsabsdivmodpowroundand sum provide common mathematical functionalityan additional math module will be introduced in section orderingmax and min apply to any data type that supports notion of comparisonor to any collection of such values likewisesorted can be used to produce an ordered list of elements drawn from any existing collection collections/iterationsrange generates new sequence of numberslen reports the length of any existing collectionfunctions reversedallanyand map operate on arbitrary iterations as welliter and next provide general framework for iteration through elements of collectionand are discussed in section
12,760
calling syntax abs(xall(iterableany(iterablechr(integerdivmod(xyhash(objid(objinput(promptisinstance(objclsiter(iterablelen(iterablemap(fiter iter max(iterablemax(abcmin(iterablemin(abcnext(iteratoropen(filenamemodeord(charpow(xypow(xyzprint(obj obj range(stoprange(startstoprange(startstopstepreversed(sequenceround(xround(xksorted(iterablesum(iterabletype(objcommon built-in functions description return the absolute value of number return true if bool(eis true for each element return true if bool(eis true for at least one element return one-character string with the given unicode code point return ( /yx yas tupleif and are integers return an integer hash value for the object (see return the unique integer serving as an "identityfor the object return string from standard inputthe prompt is optional determine if obj is an instance of the class (or subclassreturn new iterator object for the parameter (see section return the number of elements in the given iteration return an iterator yielding the result of function calls ( for respective elements iter iter return the largest element of the given iteration return the largest of the arguments return the smallest element of the given iteration return the smallest of the arguments return the next element reported by the iterator (see section open file with the given name and access mode return the unicode code point of the given character return the value xy (as an integer if and are integers)equivalent to return the value (xy mod zas an integer print the argumentswith separating spaces and trailing newline construct an iteration of values stop construct an iteration of values startstart stop construct an iteration of values startstart stepstart stepreturn an iteration of the sequence in reverse return the nearest int value ( tie is broken toward the even valuereturn the value rounded to the nearest - (return-type matches xreturn list containing elements of the iterable in sorted order return the sum of the elements in the iterable (must be numericreturn the class to which the instance obj belongs table commonly used built-in function in python
12,761
simple input and output in this sectionwe address the basics of input and output in pythondescribing standard input and output through the user consoleand python' support for reading and writing text files console input and output the print function the built-in functionprintis used to generate standard output to the console in its simplest formit prints an arbitrary sequence of argumentsseparated by spacesand followed by trailing newline character for examplethe command printmaroon outputs the string maroon \ note that arguments need not be string instances nonstring argument will be displayed as str(xwithout any argumentsthe command printoutputs single newline character the print function can be customized through the use of the following keyword parameters (see section for discussion of keyword parameters)by defaultthe print function inserts separating space into the output between each pair of arguments the separator can be customized by providing desired separating string as keyword parametersep for examplecolonseparated output can be produced as print(abcsepthe separating string need not be single characterit can be longer stringand it can be the empty stringsepcausing successive arguments to be directly concatenated by defaulta trailing newline is output after the final argument an alternative trailing string can be designated using keyword parameterend designating the empty string endsuppresses all trailing characters by defaultthe print function sends its output to the standard console howeveroutput can be directed to file by indicating an output file stream (see section using file as keyword parameter the input function the primary means for acquiring information from the user console is built-in function named input this function displays promptif given as an optional parameterand then waits until the user enters some sequence of characters followed by the return key the formal return value of the function is the string of characters that were entered strictly before the return key ( no newline character exists in the returned string
12,762
when reading numeric value from the usera programmer must use the input function to get the string of charactersand then use the int or float syntax to construct the numeric value that character string represents that isif call to response inputreports that the user entered the characters the syntax int(responsecould be used to produce the integer value it is quite common to combine these operations with syntax such as year int(inputin what year were you born)if we assume that the user will enter an appropriate response (in section we discuss error handling in such situation because input returns string as its resultuse of that function can be combined with the existing functionality of the string classas described in appendix for exampleif the user enters multiple pieces of information on the same lineit is common to call the split method on the resultas in reply inputenter and yseparated by spacespieces reply splitreturns list of stringsas separated by spaces float(pieces[ ] float(pieces[ ] sample program here is simplebut completeprogram that demonstrates the use of the input and print functions the tools for formatting the final output is discussed in appendix age int(inputenter your age in years)max heart rate ( ageas per med sci sports exerc target max heart rate printyour target fat-burning heart rate is targetfiles files are typically accessed in python beginning with call to built-in functionnamed openthat returns proxy for interactions with the underlying file for examplethe commandfp opensample txt )attempts to open file named sample txtreturning proxy that allows read-only access to the text file the open function accepts an optional second parameter that determines the access mode the default mode is for reading other common modes are for writing to the file (causing any existing file with that name to be overwritten)or for appending to the end of an existing file although we focus on use of text filesit is possible to work with binary filesusing access modes such as rb or wb
12,763
when processing filethe proxy maintains current position within the file as an offset from the beginningmeasured in number of bytes when opening file with mode or the position is initially if opened in append modea the position is initially at the end of the file the syntax fp closecloses the file associated with proxy fpensuring that any written contents are saved summary of methods for reading and writing file is given in table calling syntax fp readfp read(kfp readlinefp readlinesfor line in fpfp seek(kfp tellfp write(stringfp writelines(seqprintfile=fpdescription return the (remainingcontents of readable file as string return the next bytes of readable file as string return (remainder of the current line of readable file as string return all (remaininglines of readable file as list of strings iterate all (remaininglines of readable file change the current position to be at the kth byte of the file return the current positionmeasured as byte-offset from the start write given string at current position of the writable file write each of the strings of the given sequence at the current position of the writable file this command does not insert any newlinesbeyond those that are embedded in the strings redirect output of print function to the file table behaviors for interacting with text file via file proxy (named fpreading from file the most basic command for reading via proxy is the read method when invoked on file proxy fpas fp read( )the command returns string representing the next bytes of the filestarting at the current position without parameterthe syntax fp readreturns the remaining contents of the file in entirety for conveniencefiles can be read line at timeusing the readline method to read one lineor the readlines method to return list of all remaining lines files also support the for-loop syntaxwith iteration being line by line ( for line in fp:writing to file when file proxy is writablefor exampleif created with access mode or text can be written using methods write or writelines for exampleif we define fp openresults txt )the syntax fp writehello world \ writes single line to the file with the given string note well that write does not explicitly add trailing newlineso desired newline characters must be embedded directly in the string parameter recall that the output of the print method can be redirected to file using keyword parameteras described in section
12,764
exception handling exceptions are unexpected events that occur during the execution of program an exception might result from logical error or an unanticipated situation in pythonexceptions (also known as errorsare objects that are raised (or thrownby code that encounters an unexpected circumstance the python interpreter can also raise an exception should it encounter an unexpected conditionlike running out of memory raised error may be caught by surrounding context that "handlesthe exception in an appropriate fashion if uncaughtan exception causes the interpreter to stop executing the program and to report an appropriate message to the console in this sectionwe examine the most common error types in pythonthe mechanism for catching and handling errors that have been raisedand the syntax for raising errors from within user-defined blocks of code common exception types python includes rich hierarchy of exception classes that designate various categories of errorstable shows many of those classes the exception class serves as base class for most other error types an instance of the various subclasses encodes details about problem that has occurred several of these errors may be raised in exceptional cases by behaviors introduced in this for exampleuse of an undefined identifier in an expression causes nameerrorand errant use of the dot notationas in foo bar)will generate an attributeerror if object foo does not support member named bar class exception attributeerror eoferror ioerror indexerror keyerror keyboardinterrupt nameerror stopiteration typeerror valueerror zerodivisionerror description base class for most error types raised by syntax obj fooif obj has no member named foo raised if "end of filereached for console or file input raised upon failure of / operation ( opening fileraised if index to sequence is out of bounds raised if nonexistent key requested for set or dictionary raised if user types ctrl- while program is executing raised if nonexistent identifier used raised by next(iteratorif no elementsee section raised when wrong type of parameter is sent to function raised when parameter has invalid value ( sqrt(- )raised when any division operator used with as divisor table common exception classes in python
12,765
sending the wrong numbertypeor value of parameters to function is another common cause for an exception for examplea call to abshello will raise typeerror because the parameter is not numericand call to abs( will raise typeerror because one parameter is expected valueerror is typically raised when the correct number and type of parameters are sentbut value is illegitimate for the context of the function for examplethe int constructor accepts stringas with int )but valueerror is raised if that string does not represent an integeras with int or inthello python' sequence types ( listtupleand strraise an indexerror when syntax such as data[kis used with an integer that is not valid index for the given sequence (as described in section sets and dictionaries raise keyerror when an attempt is made to access nonexistent element raising an exception an exception is thrown by executing the raise statementwith an appropriate instance of an exception class as an argument that designates the problem for exampleif function for computing square root is sent negative value as parameterit can raise an exception with the commandraise valueerrorx cannot be negative this syntax raises newly created instance of the valueerror classwith the error message serving as parameter to the constructor if this exception is not caught within the body of the functionthe execution of the function immediately ceases and the exception is propagated to the calling context (and possibly beyondwhen checking the validity of parameters sent to functionit is customary to first verify that parameter is of an appropriate typeand then to verify that it has an appropriate value for examplethe sqrt function in python' math library performs error-checking that might be implemented as followsdef sqrt( )if not isinstance( (intfloat))raise typeerrorx must be numeric elif raise valueerrorx cannot be negative do the real work here checking the type of an object can be performed at run-time using the built-in functionisinstance in simplest formisinstance(objclsreturns true if objectobjis an instance of classclsor any subclass of that type in the above examplea more general form is used with tuple of allowable types indicated with the second parameter after confirming that the parameter is numericthe function enforces an expectation that the number be nonnegativeraising valueerror otherwise
12,766
how much error-checking to perform within function is matter of debate checking the type and value of each parameter demands additional execution time andif taken to an extremeseems counter to the nature of python consider the built-in sum functionwhich computes sum of collection of numbers an implementation with rigorous error-checking might be written as followsdef sum(values)if not isinstance(valuescollections iterable)raise typeerrorparameter must be an iterable type total for in valuesif not isinstance( (intfloat))raise typeerrorelements must be numeric total totalv return total the abstract base classcollections iterableincludes all of python' iterable containers types that guarantee support for the for-loop syntax ( listtupleset)we discuss iterables in section and the use of modulessuch as collectionsin section within the body of the for loopeach element is verified as numeric before being added to the total far more direct and clear implementation of this function can be written as followsdef sum(values)total for in valuestotal total return total interestinglythis simple implementation performs exactly like python' built-in version of the function even without the explicit checksappropriate exceptions are raised naturally by the code in particularif values is not an iterable typethe attempt to use the for-loop syntax raises typeerror reporting that the object is not iterable in the case when user sends an iterable type that includes nonnumerical elementsuch as sum([ oops ]) typeerror is naturally raised by the evaluation of expression total the error message unsupported operand type(sfor +'floatand 'strshould be sufficiently informative to the caller perhaps slightly less obvious is the error that results from sum(alpha beta ]it will technically report failed attempt to add an int and strdue to the initial evaluation of total alpha when total has been initialized to in the remainder of this bookwe tend to favor the simpler implementations in the interest of clean presentationperforming minimal error-checking in most situations
12,767
catching an exception there are several philosophies regarding how to cope with possible exceptional cases when writing code for exampleif division / is to be computedthere is clear risk that zerodivisionerror will be raised when variable has value in an ideal situationthe logic of the program may dictate that has nonzero valuethereby removing the concern for error howeverfor more complex codeor in case where the value of depends on some external input to the programthere remains some possibility of an error one philosophy for managing exceptional cases is to "look before you leap the goal is to entirely avoid the possibility of an exception being raised through the use of proactive conditional test revisiting our division examplewe might avoid the offending situation by writingif ! ratio elsedo something else second philosophyoften embraced by python programmersis that "it is easier to ask for forgiveness than it is to get permission this quote is attributed to grace hopperan early pioneer in computer science the sentiment is that we need not spend extra execution time safeguarding against every possible exceptional caseas long as there is mechanism for coping with problem after it arises in pythonthis philosophy is implemented using try-except control structure revising our first examplethe division operation can be guarded as followstryratio except zerodivisionerrordo something else in this structurethe "tryblock is the primary code to be executed although it is single command in this exampleit can more generally be larger block of indented code following the try-block are one or more "exceptcaseseach with an identified error type and an indented block of code that should be executed if the designated error is raised within the try-block the relative advantage of using try-except structure is that the non-exceptional case runs efficientlywithout extraneous checks for the exceptional condition howeverhandling the exceptional case requires slightly more time when using tryexcept structure than with standard conditional statement for this reasonthe try-except clause is best used when there is reason to believe that the exceptional case is relatively unlikelyor when it is prohibitively expensive to proactively evaluate condition to avoid the exception
12,768
exception handling is particularly useful when working with user inputor when reading from or writing to filesbecause such interactions are inherently less predictable in section we suggest the syntaxfp opensample txt )for opening file with read access that command may raise an ioerror for variety of reasonssuch as non-existent fileor lack of sufficient privilege for opening file it is significantly easier to attempt the command and catch the resulting error than it is to accurately predict whether the command will succeed we continue by demonstrating few other forms of the try-except syntax exceptions are objects that can be examined when caught to do soan identifier must be established with syntax as followstryfp opensample txt except ioerror as eprintunable to open the fileein this casethe nameedenotes the instance of the exception that was thrownand printing it causes detailed error message to be displayed ( "file not found" try-statement may handle more than one type of exception for exampleconsider the following command from section age int(inputenter your age in years)this command could fail for variety of reasons the call to input will raise an eoferror if the console input fails if the call to input completes successfullythe int constructor raises valueerror if the user has not entered characters representing valid integer if we want to handle two or more types of errors in the same waywe can use single except-statementas in the following exampleage - an initially invalid choice while age < tryage int(inputenter your age in years)if age < printyour age must be positive except (valueerroreoferror)printinvalid response we use the tuple(valueerroreoferror)to designate the types of errors that we wish to catch with the except-clause in this implementationwe catch either errorprint responseand continue with another pass of the enclosing while loop we note that when an error is raised within the try-blockthe remainder of that body is immediately skipped in this exampleif the exception arises within the call to inputor the subsequent call to the int constructorthe assignment to age never occursnor the message about needing positive value because the value of age
12,769
will be unchangedthe while loop will continue if we preferred to have the while loop continue without printing the invalid response messagewe could have written the exception-clause as except (valueerroreoferror)pass the keywordpassis statement that does nothingyet it can serve syntactically as body of control structure in this waywe quietly catch the exceptionthereby allowing the surrounding while loop to continue in order to provide different responses to different types of errorswe may use two or more except-clauses as part of try-structure in our previous examplean eoferror suggests more insurmountable error than simply an errant value being entered in that casewe might wish to provide more specific error messageor perhaps to allow the exception to interrupt the loop and be propagated to higher context we could implement such behavior as followsage - an initially invalid choice while age < tryage int(inputenter your age in years)if age < printyour age must be positive except valueerrorprintthat is an invalid age specification except eoferrorprintthere was an unexpected error reading input raise let re-raise this exception in this implementationwe have separate except-clauses for the valueerror and eoferror cases the body of the clause for handling an eoferror relies on another technique in python it uses the raise statement without any subsequent argumentto re-raise the same exception that is currently being handled this allows us to provide our own response to the exceptionand then to interrupt the while loop and propagate the exception upward in closingwe note two additional features of try-except structures in python it is permissible to have final except-clause without any identified error typesusing syntax except:to catch any other exceptions that occurred howeverthis technique should be used sparinglyas it is difficult to suggest how to handle an error of an unknown type try-statement can have finally clausewith body of code that will always be executed in the standard or exceptional caseseven when an uncaught or re-raised exception occurs that block is typically used for critical cleanup worksuch as closing an open file
12,770
iterators and generators in section we introduced the for-loop syntax beginning asfor element in iterableand we noted that there are many types of objects in python that qualify as being iterable basic container typessuch as listtupleand setqualify as iterable types furthermorea string can produce an iteration of its charactersa dictionary can produce an iteration of its keysand file can produce an iteration of its lines userdefined types may also support iteration in pythonthe mechanism for iteration is based upon the following conventionsan iterator is an object that manages an iteration through series of values if variableiidentifies an iterator objectthen each call to the built-in functionnext( )produces subsequent element from the underlying serieswith stopiteration exception raised to indicate that there are no further elements an iterable is an objectobjthat produces an iterator via the syntax iter(objby these definitionsan instance of list is an iterablebut not itself an iterator with data [ ]it is not legal to call next(datahoweveran iterator object can be produced with syntaxi iter(data)and then each subsequent call to next(iwill return an element of that list the for-loop syntax in python simply automates this processcreating an iterator for the give iterableand then repeatedly calling for the next element until catching the stopiteration exception more generallyit is possible to create multiple iterators based upon the same iterable objectwith each iterator maintaining its own state of progress howeveriterators typically maintain their state with indirect reference back to the original collection of elements for examplecalling iter(dataon list instance produces an instance of the list iterator class that iterator does not store its own copy of the list of elements insteadit maintains current index into the original listrepresenting the next element to be reported thereforeif the contents of the original list are modified after the iterator is constructedbut before the iteration is completethe iterator will be reporting the updated contents of the list python also supports functions and classes that produce an implicit iterable series of valuesthat iswithout constructing data structure to store all of its values at once for examplethe call range( does not return list of numbersit returns range object that is iterable this object generates the million values one at timeand only as needed such lazy evaluation technique has great advantage in the case of rangeit allows loop of the formfor in range( ):to execute without setting aside memory for storing one million values alsoif such loop were to be interrupted in some fashionno time will have been spent computing unused values of the range
12,771
we see lazy evaluation used in many of python' libraries for examplethe dictionary class supports methods keys)values)and items)which respectively produce "viewof all keysvaluesor (key,valuepairs within dictionary none of these methods produces an explicit list of results insteadthe views that are produced are iterable objects based upon the actual contents of the dictionary an explicit list of values from such an iteration can be immediately constructed by calling the list class constructor with the iteration as parameter for examplethe syntax list(range( )produces list instance with values from to while the syntax list( values)produces list that has elements based upon the current values of dictionary we can similarly construct tuple or set instance based upon given iterable generators in section we will explain how to define class whose instances serve as iterators howeverthe most convenient technique for creating iterators in python is through the use of generators generator is implemented with syntax that is very similar to functionbut instead of returning valuesa yield statement is executed to indicate each element of the series as an exampleconsider the goal of determining all factors of positive integer for examplethe number has factors traditional function might produce and return list containing all factorsimplemented asdef factors( )results for in range( , + )if = results append(kreturn results traditional function that computes factors store factors in new list divides evenlythus is factor add to the list of factors return the entire list in contrastan implementation of generator for computing those factors could be implemented as followsdef factors( )for in range( , + )if = yield generator that computes factors divides evenlythus is factor yield this factor as next result notice use of the keyword yield rather than return to indicate result this indicates to python that we are defining generatorrather than traditional function it is illegal to combine yield and return statements in the same implementationother than zero-argument return statement to cause generator to end its execution if programmer writes loop such as for factor in factors( ):an instance of our generator is created for each iteration of the looppython executes our procedure
12,772
until yield statement indicates the next value at that pointthe procedure is temporarily interruptedonly to be resumed when another value is requested when the flow of control naturally reaches the end of our procedure (or zero-argument return statement) stopiteration exception is automatically raised although this particular example uses single yield statement in the source codea generator can rely on multiple yield statements in different constructswith the generated series determined by the natural flow of control for examplewe can greatly improve the efficiency of our generator for computing factors of numbernby only testing values up to the square root of that numberwhile reporting the factor // that is associated with each (unless // equals kwe might implement such generator as followsdef factors( ) = while nif = yield yield / + if =nyield generator that computes factors while sqrt(nspecial case if is perfect square we should note that this generator differs from our first version in that the factors are not generated in strictly increasing order for examplefactors( generates the series in closingwe wish to emphasize the benefits of lazy evaluation when using generator rather than traditional function the results are only computed if requestedand the entire series need not reside in memory at one time in facta generator can effectively produce an infinite series of values as an examplethe fibonacci numbers form classic mathematical sequencestarting with value then value and then each subsequent value being the sum of the two preceding values hencethe fibonacci series begins as the following generator produces this infinite series def fibonacci) = = while trueyield future = future keep going report valueaduring this pass this will be next value reported and subsequently this
12,773
additional python conveniences in this sectionwe introduce several features of python that are particularly convenient for writing cleanconcise code each of these syntaxes provide functionality that could otherwise be accomplished using functionality that we have introduced earlier in this howeverat timesthe new syntax is more clear and direct expression of the logic conditional expressions python supports conditional expression syntax that can replace simple control structure the general syntax is an expression of the formexpr if condition else expr this compound expression evaluates to expr if the condition is trueand otherwise evaluates to expr for those familiar with java or ++this is equivalent to the syntaxcondition expr expr in those languages as an exampleconsider the goal of sending the absolute value of variablento function (and without relying on the built-in abs functionfor the sake of exampleusing traditional control structurewe might accomplish this as followsif > param elseparam - result foo(paramcall the function with the conditional expression syntaxwe can directly assign value to variableparamas followsparam if > else - result foo(parampick the appropriate value call the function in factthere is no need to assign the compound expression to variable conditional expression can itself serve as parameter to the functionwritten as followsresult foo( if > else -nsometimesthe mere shortening of source code is advantageous because it avoids the distraction of more cumbersome control structure howeverwe recommend that conditional expression be used only when it improves the readability of the source codeand when the first of the two options is the more "naturalcasegiven its prominence in the syntax (we prefer to view the alternative value as more exceptional
12,774
comprehension syntax very common programming task is to produce one series of values based upon the processing of another series oftenthis task can be accomplished quite simply in python using what is known as comprehension syntax we begin by demonstrating list comprehensionas this was the first form to be supported by python its general form is as followsexpression for value in iterable if condition we note that both expression and condition may depend on valueand that the if-clause is optional the evaluation of the comprehension is logically equivalent to the following traditional control structure for computing resulting listresult for value in iterableif conditionresult append(expressionas concrete examplea list of the squares of the numbers from to nthat is [ ]can be created by traditional means as followssquares for in range( + )squares append( kwith list comprehensionthis logic is expressed as followssquares [ for in range( + )as second examplesection introduced the goal of producing list of factors for an integer that task is accomplished with the following list comprehensionfactors [ for in range( , + if = python supports similar comprehension syntaxes that respectively produce setgeneratoror dictionary we compare those syntaxes using our example for producing the squares of numbers for in range( + for in range( + for in range( + for in range( + list comprehension set comprehension generator comprehension dictionary comprehension the generator syntax is particularly attractive when results do not need to be stored in memory for exampleto compute the sum of the first squaresthe generator syntaxtotal sum( for in range( + ))is preferred to the use of an explicitly instantiated list comprehension as the parameter
12,775
packing and unpacking of sequences python provides two additional conveniences involving the treatment of tuples and other sequence types the first is rather cosmetic if series of comma-separated expressions are given in larger contextthey will be treated as single tupleeven if no enclosing parentheses are provided for examplethe assignment data results in identifierdatabeing assigned to the tuple ( this behavior is called automatic packing of tuple one common use of packing in python is when returning multiple values from function if the body of function executes the commandreturn xy it will be formally returning single object that is the tuple (xyas dual to the packing behaviorpython can automatically unpack sequenceallowing one to assign series of individual identifiers to the elements of sequence as an examplewe can write abcd range( which has the effect of assigning = = = and = as those are the four values in the sequence returned by the call to range for this syntaxthe right-hand side expression can be any iterable typeas long as the number of variables on the left-hand side is the same as the number of elements in the iteration this technique can be used to unpack tuples returned by function for examplethe built-in functiondivmod(ab)returns the pair of values ( /ba bassociated with an integer division although the caller can consider the return value to be single tupleit is possible to write quotientremainder divmod(abto separately identify the two entries of the returned tuple this syntax can also be used in the context of for loopwhen iterating over sequence of iterablesas in for xy in ( )( )( ]in this examplethere will be three iterations of the loop during the first passx= and = and so on this style of loop is quite commonly used to iterate through key-value pairs that are returned by the itemsmethod of the dict classas infor kv in mapping items)
12,776
simultaneous assignments the combination of automatic packing and unpacking forms technique known as simultaneous assignmentwhereby we explicitly assign series of values to series of identifiersusing syntaxxyz in effectthe right-hand side of this assignment is automatically packed into tupleand then automatically unpacked with its elements assigned to the three identifiers on the left-hand side when using simultaneous assignmentall of the expressions are evaluated on the right-hand side before any of the assignments are made to the left-hand variables this is significantas it provides convenient means for swapping the values associated with two variablesjk kj with this commandj will be assigned to the old value of kand will be assigned to the old value of without simultaneous assignmenta swap typically requires more delicate use of temporary variablesuch as temp = temp with the simultaneous assignmentthe unnamed tuple representing the packed values on the right-hand side implicitly serves as the temporary variable when performing such swap the use of simultaneous assignments can greatly simplify the presentation of code as an examplewe reconsider the generator on page that produces the fibonacci series the original code requires separate initialization of variables and to begin the series within each pass of the loopthe goal was to reassign and brespectivelyto the values of and + at the timewe accomplished this with brief use of third variable with simultaneous assignmentsthat generator can be implemented more directly as followsdef fibonacci)ab while trueyield ab ba+
12,777
scopes and namespaces when computing sum with the syntax in pythonthe names and must have been previously associated with objects that serve as valuesa nameerror will be raised if no such definitions are found the process of determining the value associated with an identifier is known as name resolution whenever an identifier is assigned to valuethat definition is made with specific scope top-level assignments are typically made in what is known as global scope assignments made within the body of function typically have scope that is local to that function call thereforean assignmentx within function has no effect on the identifierxin the broader scope each distinct scope in python is represented using an abstraction known as namespace namespace manages all identifiers that are currently defined in given scope figure portrays two namespacesone being that of caller to our count function from section and the other being the local namespace during the execution of that function str float gpa grades str major list target data int item cs str str str abafigure portrayal of the two namespaces associated with user' call count(gradesa )as defined in section the left namespace is the caller' and the right namespace represents the local scope of the function python implements namespace with its own dictionary that maps each identifying string ( to its associated value python provides several ways to examine given namespace the functiondirreports the names of the identifiers in given namespace ( the keys of the dictionary)while the functionvarsreturns the full dictionary by defaultcalls to dirand varsreport on the most locally enclosing namespace in which they are executed
12,778
when an identifier is indicated in commandpython searches series of namespaces in the process of name resolution firstthe most locally enclosing scope is searched for given name if not found therethe next outer scope is searchedand so on we will continue our examination of namespacesin section when discussing python' treatment of object-orientation we will see that each object has its own namespace to store its attributesand that classes each have namespace as well first-class objects in the terminology of programming languagesfirst-class objects are instances of type that can be assigned to an identifierpassed as parameteror returned by function all of the data types we introduced in section such as int and listare clearly first-class types in python in pythonfunctions and classes are also treated as first-class objects for examplewe could write the followingscream print screamhello assign name 'screamto the function denoted as 'printcall that function in this casewe have not created new functionwe have simply defined scream as an alias for the existing print function while there is little motivation for precisely this exampleit demonstrates the mechanism that is used by python to allow one function to be passed as parameter to another on page we noted that the built-in functionmaxaccepts an optional keyword parameter to specify non-default order when computing maximum for examplea caller can use the syntaxmax(abkey=abs)to determine which value has the larger absolute value within the body of that functionthe formal parameterkeyis an identifier that will be assigned to the actual parameterabs in terms of namespacesan assignment such as scream printintroduces the identifierscreaminto the current namespacewith its value being the object that represents the built-in functionprint the same mechanism is applied when userdefined function is declared for exampleour count function from section beings with the following syntaxdef count(datatarget)such declaration introduces the identifiercountinto the current namespacewith the value being function instance representing its implementation in similar fashionthe name of newly defined class is associated with representation of that class as its value (class definitions will be introduced in the next
12,779
modules and the import statement we have already introduced many functions ( maxand classes ( listthat are defined within python' built-in namespace depending on the version of pythonthere are approximately - definitions that were deemed significant enough to be included in that built-in namespace beyond the built-in definitionsthe standard python distribution includes perhaps tens of thousands of other valuesfunctionsand classes that are organized in additional librariesknown as modulesthat can be imported from within program as an examplewe consider the math module while the built-in namespace includes few mathematical functions ( absminmaxround)many more are relegated to the math module ( sincossqrtthat module also defines approximate values for the mathematical constantspi and python' import statement loads definitions from module into the current namespace one form of an import statement uses syntax such as the followingfrom math import pisqrt this command adds both pi and sqrtas defined in the math moduleinto the current namespaceallowing direct use of the identifierpior call of the functionsqrt( if there are many definitions from the same module to be importedan asterisk may be used as wild cardas infrom math import but this form should be used sparingly the danger is that some of the names defined in the module may conflict with names already in the current namespace (or being imported from another module)and the import causes the new definitions to replace existing ones another approach that can be used to access many definitions from the same module is to import the module itselfusing syntax such asimport math formallythis adds the identifiermathto the current namespacewith the module as its value (modules are also first-class objects in python once importedindividual definitions from the module can be accessed using fully-qualified namesuch as math pi or math sqrt( creating new module to create new moduleone simply has to put the relevant definitions in file named with py suffix those definitions can be imported from any other py file within the same project directory for exampleif we were to put the definition of our count function (see section into file named utility pywe could import that function using the syntaxfrom utility import count
12,780
it is worth noting that top-level commands with the module source code are executed when the module is first importedalmost as if the module were its own script there is special construct for embedding commands within the module that will be executed if the module is directly invoked as scriptbut not when the module is imported from another script such commands should be placed in body of conditional statement of the following formif name =__main__ using our hypothetical utility py module as an examplesuch commands will be executed if the interpreter is started with command python utility pybut not when the utility module is imported into another context this approach is often used to embed what are known as unit tests within the modulewe will discuss unit testing further in section existing modules table provides summary of few available modules that are relevant to study of data structures we have already discussed the math module briefly in the remainder of this sectionwe highlight another module that is particularly important for some of the data structures and algorithms that we will study later in this book existing modules module name array collections copy heapq math os random re sys time description provides compact array storage for primitive types defines additional data structures and abstract base classes involving collections of objects defines general functions for making copies of objects provides heap-based priority queue functions (see section defines common mathematical constants and functions provides support for interactions with the operating system provides random number generation provides support for processing regular expressions provides additional level of interaction with the python interpreter provides support for measuring timeor delaying program table some existing python modules relevant to data structures and algorithms pseudo-random number generation python' random module provides the ability to generate pseudo-random numbersthat isnumbers that are statistically random (but not necessarily truly randoma pseudo-random number generator uses deterministic formula to generate the
12,781
next number in sequence based upon one or more past numbers that it has generated indeeda simple yet popular pseudo-random number generator chooses its next number based solely on the most recently chosen number and some additional parameters using the following formula next ( *current bnwhere aband are appropriately chosen integers python uses more advanced technique known as mersenne twister it turns out that the sequences generated by these techniques can be proven to be statistically uniformwhich is usually good enough for most applications requiring random numberssuch as games for applicationssuch as computer security settingswhere one needs unpredictable random sequencesthis kind of formula should not be used insteadone should ideally sample from source that is actually randomsuch as radio static coming from outer space since the next number in pseudo-random generator is determined by the previous number( )such generator always needs place to startwhich is called its seed the sequence of numbers generated for given seed will always be the same one common trick to get different sequence each time program is run is to use seed that will be different for each run for examplewe could use some timed input from user or the current system time in milliseconds python' random module provides support for pseudo-random number generation by defining random classinstances of that class serve as generators with independent state this allows different aspects of program to rely on their own pseudo-random number generatorso that calls to one generator do not affect the sequence of numbers produced by another for convenienceall of the methods supported by the random class are also supported as stand-alone functions of the random module (essentially using single generator instance for all top-level callssyntax seed(hashablerandomrandint( ,brandrange(startstopstepchoice(seqshuffle(seqdescription initializes the pseudo-random number generator based upon the hash value of the parameter returns pseudo-random floating-point value in the interval [ returns pseudo-random integer in the closed interval [abreturns pseudo-random integer in the standard python range indicated by the parameters returns an element of the given sequence chosen pseudo-randomly reorders the elements of the given sequence pseudo-randomly table methods supported by instances of the random classand as top-level functions of the random module
12,782
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - write short python functionis multiple(nm)that takes two integer values and returns true if is multiple of mthat isn mi for some integer iand false otherwise - write short python functionis even( )that takes an integer value and returns true if is evenand false otherwise howeveryour function cannot use the multiplicationmoduloor division operators - write short python functionminmax(data)that takes sequence of one or more numbersand returns the smallest and largest numbersin the form of tuple of length two do not use the built-in functions min or max in implementing your solution - write short python function that takes positive integer and returns the sum of the squares of all the positive integers smaller than - give single command that computes the sum from exercise - relying on python' comprehension syntax and the built-in sum function - write short python function that takes positive integer and returns the sum of the squares of all the odd positive integers smaller than - give single command that computes the sum from exercise - relying on python' comprehension syntax and the built-in sum function - python allows negative integers to be used as indices into sequencesuch as string if string has length nand expression [kis used for index - such that [jreferences the same elementr- what parameters should be sent to the range constructorto produce range with values - what parameters should be sent to the range constructorto produce range with values - - - - - demonstrate how to use python' list comprehension syntax to produce the list [ - python' random module includes function choice(datathat returns random element from non-empty sequence the random module includes more basic function randrangewith parameterization similar to the built-in range functionthat return random choice from the given range using only the randrange functionimplement your own version of the choice function
12,783
creativity - write pseudo-code description of function that reverses list of integersso that the numbers are listed in the opposite order than they were beforeand compare this method to an equivalent python function for doing the same thing - write short python function that takes sequence of integer values and determines if there is distinct pair of numbers in the sequence whose product is odd - write python function that takes sequence of numbers and determines if all the numbers are different from each other (that isthey are distinctc- in our implementation of the scale function (page )the body of the loop executes the command data[jfactor we have discussed that numeric types are immutableand that use of the operator in this context causes the creation of new instance (not the mutation of an existing instancehow is it still possiblethenthat our implementation of scale changes the actual parameter sent by the callerc- had we implemented the scale function (page as followsdoes it work properlydef scale(datafactor)for val in dataval factor explain why or why not - demonstrate how to use python' list comprehension syntax to produce the list [ - demonstrate how to use python' list comprehension syntax to produce the list ]but without having to type all such characters literally - python' random module includes function shuffle(datathat accepts list of elements and randomly reorders the elements so that each possible order occurs with equal probability the random module includes more basic function randint(abthat returns uniformly random integer from to (including both endpointsusing only the randint functionimplement your own version of the shuffle function - write python program that repeatedly reads lines from standard input until an eoferror is raisedand then outputs those lines in reverse order ( user can indicate end of input by typing ctrl-
12,784
- write short python program that takes two arrays and of length storing int valuesand returns the dot product of and that isit returns an array of length such that [ia[ib[ ]for - give an example of python code fragment that attempts to write an element to list based on an index that may be out of bounds if that index is out of boundsthe program should catch the exception that resultsand print the following error message"don' try buffer overflow attacks in python! - write short python function that counts the number of vowels in given character string - write short python function that takes string srepresenting sentenceand returns copy of the string with all punctuation removed for exampleif given the string "let trymike "this function would return "lets try mikec- write short program that takes as input three integersaband cfrom the console and determines if they can be used in correct arithmetic formula (in the given order)like " ," ,or " - in section we provided three different implementations of generator that computes factors of given integer the third of those implementationsfrom page was the most efficientbut we noted that it did not yield the factors in increasing order modify the generator so that it reports factors in increasing orderwhile maintaining its general performance advantages - the -norm of vector ( vn in -dimensional space is defined as vv vnp for the special case of this results in the traditional euclidean normwhich represents the length of the vector for examplethe euclidean norm of two-dimensional with coordinates ( has vector euclidean norm of give an implementation of function named norm such that norm(vpreturns the -norm value of and norm(vreturns the euclidean norm of you may assume that is list of numbers
12,785
projects - write python program that outputs all possible strings formed by using the characters and exactly once - write python program that can take positive integer greater than as input and write out the number of times one must repeatedly divide this number by before getting value less than - write python program that can "make change your program should take two numbers as inputone that is monetary amount charged and the other that is monetary amount given it should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged the values assigned to the bills and coins can be based on the monetary system of any current or former government try to design your program so that it returns as few bills and coins as possible - write python program that can simulate simple calculatorusing the console as the exclusive input and output device that iseach input to the calculatorbe it numberlike or or an operatorlike or =can be done on separate line after each such inputyou should output to the python console what would be displayed on your calculator - write python program that simulates handheld calculator your program should process input from the python console representing buttons that are "pushed,and then output the contents of the screen after each operation is performed minimallyyour calculator should be able to process the basic arithmetic operations and reset/clear operation - common punishment for school children is to write out sentence multiple times write python stand-alone program that will write out the following sentence one hundred times" will never spam my friends again your program should number each of the sentences and it should make eight different random-looking typos - the birthday paradox says that the probability that two people in room will have the same birthday is more than halfprovided nthe number of people in the roomis more than this property is not really paradoxbut many people find it surprising design python program that can test this paradox by series of experiments on randomly generated birthdayswhich test this paradox for - write python program that inputs list of wordsseparated by whitespaceand outputs how many times each word appears in the list you need not worry about efficiency at this pointhoweveras this topic is something that will be addressed later in this book
12,786
notes the official python web site (modules the python interpreter is itself useful referenceas the interactive command help(fooprovides documentation for any functionclassor module that foo identifies books providing an introduction to programming in python include titles authored by campbell et al [ ]cedar [ ]dawson [ ]goldwasser and letscher [ ]lutz [ ]perkovic [ ]and zelle [ more complete reference books on python include titles by beazley [ ]and summerfield [
12,787
object-oriented programming contents goalsprinciplesand patterns object-oriented design goals object-oriented design principles design patterns software development design pseudo-code coding style and documentation testing and debugging class definitions examplecreditcard class operator overloading and python' special methods examplemultidimensional vector class iterators examplerange class inheritance extending the creditcard class hierarchy of numeric progressions abstract base classes namespaces and object-orientation instance and class namespaces name resolution and dynamic dispatch shallow and deep copying exercises
12,788
goalsprinciplesand patterns as the name impliesthe main "actorsin the object-oriented paradigm are called objects each object is an instance of class each class presents to the outside world concise and consistent view of the objects that are instances of this classwithout going into too much unnecessary detail or giving others access to the inner workings of the objects the class definition typically specifies instance variablesalso known as data membersthat the object containsas well as the methodsalso known as member functionsthat the object can execute this view of computing is intended to fulfill several goals and incorporate several design principleswhich we discuss in this object-oriented design goals software implementations should achieve robustnessadaptabilityand reusability (see figure robustness adaptability reusability figure goals of object-oriented design robustness every good programmer wants to develop software that is correctwhich means that program produces the right output for all the anticipated inputs in the program' application in additionwe want software to be robustthat iscapable of handling unexpected inputs that are not explicitly defined for its application for exampleif program is expecting positive integer (perhaps representing the price of an itemand instead is given negative integerthen the program should be able to recover gracefully from this error more importantlyin life-critical applicationswhere software error can lead to injury or loss of lifesoftware that is not robust could be deadly this point was driven home in the late in accidents involving therac- radiation-therapy machinewhich severely overdosed six patients between and some of whom died from complications resulting from their radiation overdose all six accidents were traced to software errors
12,789
adaptability modern software applicationssuch as web browsers and internet search enginestypically involve large programs that are used for many years softwarethereforeneeds to be able to evolve over time in response to changing conditions in its environment thusanother important goal of quality software is that it achieves adaptability (also called evolvabilityrelated to this concept is portabilitywhich is the ability of software to run with minimal change on different hardware and operating system platforms an advantage of writing software in python is the portability provided by the language itself reusability going hand in hand with adaptability is the desire that software be reusablethat isthe same code should be usable as component of different systems in various applications developing quality software can be an expensive enterpriseand its cost can be offset somewhat if the software is designed in way that makes it easily reusable in future applications such reuse should be done with carehoweverfor one of the major sources of software errors in the therac- came from inappropriate reuse of therac- software (which was not object-oriented and not designed for the hardware platform used with the therac- object-oriented design principles chief among the principles of the object-oriented approachwhich are intended to facilitate the goals outlined aboveare the following (see figure )modularity abstraction encapsulation modularity abstraction encapsulation figure principles of object-oriented design
12,790
modularity modern software systems typically consist of several different components that must interact correctly in order for the entire system to work properly keeping these interactions straight requires that these different components be well organized modularity refers to an organizing principle in which different components of software system are divided into separate functional units as real-world analogya house or apartment can be viewed as consisting of several interacting unitselectricalheating and coolingplumbingand structural rather than viewing these systems as one giant jumble of wiresventspipesand boardsthe organized architect designing house or apartment will view them as separate modules that interact in well-defined ways in so doinghe or she is using modularity to bring clarity of thought that provides natural way of organizing functions into distinct manageable units in like mannerusing modularity in software system can also provide powerful organizing framework that brings clarity to an implementation in pythonwe have already seen that module is collection of closely related functions and classes that are defined together in single file of source code python' standard libraries includefor examplethe math modulewhich provides definitions for key mathematical constants and functionsand the os modulewhich provides support for interacting with the operating system the use of modularity helps support the goals listed in section robustness is greatly increased because it is easier to test and debug separate components before they are integrated into larger software system furthermorebugs that persist in complete system might be traced to particular componentwhich can be fixed in relative isolation the structure imposed by modularity also helps enable software reusability if software modules are written in general waythe modules can be reused when related need arises in other contexts this is particularly relevant in study of data structureswhich can typically be designed with sufficient abstraction and generality to be reused in many applications abstraction the notion of abstraction is to distill complicated system down to its most fundamental parts typicallydescribing the parts of system involves naming them and explaining their functionality applying the abstraction paradigm to the design of data structures gives rise to abstract data types (adtsan adt is mathematical model of data structure that specifies the type of data storedthe operations supported on themand the types of parameters of the operations an adt specifies what each operation doesbut not how it does it we will typically refer to the collective set of behaviors supported by an adt as its public interface
12,791
as programming languagepython provides great deal of latitude in regard to the specification of an interface python has tradition of treating abstractions implicitly using mechanism known as duck typing as an interpreted and dynamically typed languagethere is no "compile timechecking of data types in pythonand no formal requirement for declarations of abstract base classes instead programmers assume that an object supports set of known behaviorswith the interpreter raising run-time error if those assumptions fail the description of this as "duck typingcomes from an adage attributed to poet james whitcomb rileystating that "when see bird that walks like duck and swims like duck and quacks like ducki call that bird duck more formallypython supports abstract data types using mechanism known as an abstract base class (abcan abstract base class cannot be instantiated ( you cannot directly create an instance of that class)but it defines one or more common methods that all implementations of the abstraction must have an abc is realized by one or more concrete classes that inherit from the abstract base class while providing implementations for those method declared by the abc python' abc module provides formal support for abcsalthough we omit such declarations for simplicity we will make use of several existing abstract base classes coming from python' collections modulewhich includes definitions for several common data structure adtsand concrete implementations of some of those abstractions encapsulation another important principle of object-oriented design is encapsulation different components of software system should not reveal the internal details of their respective implementations one of the main advantages of encapsulation is that it gives one programmer freedom to implement the details of componentwithout concern that other programmers will be writing code that intricately depends on those internal decisions the only constraint on the programmer of component is to maintain the public interface for the componentas other programmers will be writing code that depends on that interface encapsulation yields robustness and adaptabilityfor it allows the implementation details of parts of program to change without adversely affecting other partsthereby making it easier to fix bugs or add new functionality with relatively local changes to component throughout this bookwe will adhere to the principle of encapsulationmaking clear which aspects of data structure are assumed to be public and which are assumed to be internal details with that saidpython provides only loose support for encapsulation by conventionnames of members of class (both data members and member functionsthat start with single underscore character ( secretare assumed to be nonpublic and should not be relied upon those conventions are reinforced by the intentional omission of those members from automatically generated documentation
12,792
design patterns object-oriented design facilitates reusablerobustand adaptable software designing good code takes more than simply understanding object-oriented methodologieshowever it requires the effective use of object-oriented design techniques computing researchers and practitioners have developed variety of organizational concepts and methodologies for designing quality object-oriented software that is concisecorrectand reusable of special relevance to this book is the concept of design patternwhich describes solution to "typicalsoftware design problem pattern provides general template for solution that can be applied in many different situations it describes the main elements of solution in an abstract way that can be specialized for specific problem at hand it consists of namewhich identifies the patterna contextwhich describes the scenarios for which this pattern can be applieda templatewhich describes how the pattern is appliedand resultwhich describes and analyzes what the pattern produces we present several design patterns in this bookand we show how they can be consistently applied to implementations of data structures and algorithms these design patterns fall into two groups--patterns for solving algorithm design problems and patterns for solving software engineering problems the algorithm design patterns we discuss include the followingrecursion (amortization (sections and divide-and-conquer (section prune-and-searchalso known as decrease-and-conquer (section brute force (section dynamic programming (section the greedy method (sections and likewisethe software engineering design patterns we discuss includeiterator (sections and adapter (section position (sections and composition (sections and template method (sections and locator (section factory method (section rather than explain each of these concepts herehoweverwe introduce them throughout the text as noted above for each patternbe it for algorithm engineering or software engineeringwe explain its general use and we illustrate it with at least one concrete example
12,793
software development traditional software development involves several phases three major steps are design implementation testing and debugging in this sectionwe briefly discuss the role of these phasesand we introduce several good practices for programming in pythonincluding coding stylenaming conventionsformal documentationand unit testing design for object-oriented programmingthe design step is perhaps the most important phase in the process of developing software for it is in the design step that we decide how to divide the workings of our program into classeswe decide how these classes will interactwhat data each will storeand what actions each will perform indeedone of the main challenges that beginning programmers face is deciding what classes to define to do the work of their program while general prescriptions are hard to come bythere are some rules of thumb that we can apply when determining how to design our classesresponsibilitiesdivide the work into different actorseach with different responsibility try to describe responsibilities using action verbs these actors will form the classes for the program independencedefine the work for each class to be as independent from other classes as possible subdivide responsibilities between classes so that each class has autonomy over some aspect of the program give data (as instance variablesto the class that has jurisdiction over the actions that require access to this data behaviorsdefine the behaviors for each class carefully and preciselyso that the consequences of each action performed by class will be well understood by other classes that interact with it these behaviors will define the methods that this class performsand the set of behaviors for class are the interface to the classas these form the means for other pieces of code to interact with objects from the class defining the classestogether with their instance variables and methodsare key to the design of an object-oriented program good programmer will naturally develop greater skill in performing these tasks over timeas experience teaches him or her to notice patterns in the requirements of program that match patterns that he or she has seen before
12,794
common tool for developing an initial high-level design for project is the use of crc cards class-responsibility-collaborator (crccards are simple index cards that subdivide the work required of program the main idea behind this tool is to have each card represent componentwhich will ultimately become class in the program we write the name of each component on the top of an index card on the left-hand side of the cardwe begin writing the responsibilities for this component on the right-hand sidewe list the collaborators for this componentthat isthe other components that this component will have to interact with to perform its duties the design process iterates through an action/actor cyclewhere we first identify an action (that isa responsibility)and we then determine an actor (that isa componentthat is best suited to perform that action the design is complete when we have assigned all actions to actors in using index cards for this process (rather than larger pieces of paper)we are relying on the fact that each component should have small set of responsibilities and collaborators enforcing this rule helps keep the individual classes manageable as the design takes forma standard approach to explain and document the design is the use of uml (unified modeling languagediagrams to express the organization of program uml diagrams are standard visual notation to express object-oriented software designs several computer-aided tools are available to build uml diagrams one type of uml figure is known as class diagram an example of such diagram is given in figure for class that represents consumer credit card the diagram has three portionswith the first designating the name of the classthe second designating the recommended instance variablesand the third designating the recommended methods of the class in section we discuss our naming conventionsand in section we provide complete implementation of python creditcard class based on this design creditcard classfieldscustomer bank account balance limit behaviorsget customerget bankget accountmake payment(amountget balanceget limitcharge(pricefigure class diagram for proposed creditcard class
12,795
pseudo-code as an intermediate step before the implementation of designprogrammers are often asked to describe algorithms in way that is intended for human eyes only such descriptions are called pseudo-code pseudo-code is not computer programbut is more structured than usual prose it is mixture of natural language and high-level programming constructs that describe the main ideas behind generic implementation of data structure or algorithm because pseudo-code is designed for human readernot computerwe can communicate high-level ideaswithout being burdened with low-level implementation details at the same timewe should not gloss over important steps like many forms of human communicationfinding the right balance is an important skill that is refined through practice in this bookwe rely on pseudo-code style that we hope will be evident to python programmersyet with mix of mathematical notations and english prose for examplewe might use the phrase "indicate an errorrather than formal raise statement following conventions of pythonwe rely on indentation to indicate the extent of control structures and on an indexing notation in which entries of sequence with length are indexed from [ to [ howeverwe choose to enclose comments within curly braces like these in our pseudo-coderather than using python' character coding style and documentation programs should be made easy to read and understand good programmers should therefore be mindful of their coding styleand develop style that communicates the important aspects of program' design for both humans and computers conventions for coding style tend to vary between different programming communities the official style guide for python code is available online at the main principles that we adopt are as followspython code blocks are typically indented by spaces howeverto avoid having our code fragments overrun the book' marginswe use spaces for each level of indentation it is strongly recommended that tabs be avoidedas tabs are displayed with differing widths across systemsand tabs and spaces are not viewed as identical by the python interpreter many python-aware editors will automatically replace tabs with an appropriate number of spaces
12,796
use meaningful names for identifiers try to choose names that can be read aloudand choose names that reflect the actionresponsibilityor data each identifier is naming classes (other than python' built-in classesshould have name that serves as singular nounand should be capitalized ( date rather than date or dateswhen multiple words are concatenated to form class namethey should follow the so-called "camelcaseconvention in which the first letter of each word is capitalized ( creditcardfunctionsincluding member functions of classshould be lowercase if multiple words are combinedthey should be separated by underscores ( make paymentthe name of function should typically be verb that describes its affect howeverif the only purpose of the function is to return valuethe function name may be noun that describes the value ( sqrt rather than calculate sqrtnames that identify an individual object ( parameterinstance variableor local variableshould be lowercase noun ( priceoccasionallywe stray from this rule when using single uppercase letter to designate the name of data structures (such as tree tidentifiers that represent value considered to be constant are traditionally identified using all capital letters and with underscores to separate words ( max sizerecall from our discussion of encapsulation that identifiers in any context that begin with single leading underscore ( secretare intended to suggest that they are only for "internaluse to class or moduleand not part of public interface use comments that add meaning to program and explain ambiguous or confusing constructs in-line comments are good for quick explanationsthey are indicated in python following the characteras in if = is odd multiline block comments are good for explaining more complex code sections in pythonthese are technically multiline string literalstypically delimited with triple quotes (""")which have no effect when executed in the next sectionwe discuss the use of block comments for documentation
12,797
documentation python provides integrated support for embedding formal documentation directly in source code using mechanism known as docstring formallyany string literal that appears as the first statement within the body of moduleclassor function (including member function of classwill be considered to be docstring by conventionthose string literals should be delimited within triple quotes ("""as an exampleour version of the scale function from page could be documented as followsdef scale(datafactor)"""multiply all entries of numeric data list by the given factor ""for in range(len(data))data[jfactor it is common to use the triple-quoted string delimiter for docstringeven when the string fits on single lineas in the above example more detailed docstrings should begin with single line that summarizes the purposefollowed by blank lineand then further details for examplewe might more clearly document the scale function as followsdef scale(datafactor)"""multiply all entries of numeric data list by the given factor data an instance of any mutable sequence type (such as listcontaining numeric elements factor number that serves as the multiplicative factor for scaling ""for in range(len(data))data[jfactor docstring is stored as field of the modulefunctionor class in which it is declared it serves as documentation and can be retrieved in variety of ways for examplethe command help( )within the python interpreterproduces the documentation associated with the identified object an external tool named pydoc is distributed with python and can be used to generate formal documentation as text or as web page guidelines for authoring useful docstrings are available atin this bookwe will try to present docstrings when space allows omitted docstrings can be found in the online version of our source code
12,798
testing and debugging testing is the process of experimentally checking the correctness of programwhile debugging is the process of tracking the execution of program and discovering the errors in it testing and debugging are often the most time-consuming activity in the development of program testing careful testing plan is an essential part of writing program while verifying the correctness of program over all possible inputs is usually infeasiblewe should aim at executing the program on representative subset of inputs at the very minimumwe should make sure that every method of class is tested at least once (method coverageeven bettereach code statement in the program should be executed at least once (statement coverageprograms often tend to fail on special cases of the input such cases need to be carefully identified and tested for examplewhen testing method that sorts (that isputs in ordera sequence of integerswe should consider the following inputsthe sequence has zero length (no elementsthe sequence has one element all the elements of the sequence are the same the sequence is already sorted the sequence is reverse sorted in addition to special inputs to the programwe should also consider special conditions for the structures used by the program for exampleif we use python list to store datawe should make sure that boundary casessuch as inserting or removing at the beginning or end of the listare properly handled while it is essential to use handcrafted test suitesit is also advantageous to run the program on large collection of randomly generated inputs the random module in python provides several means for generating random numbersor for randomizing the order of collections the dependencies among the classes and functions of program induce hierarchy namelya component is above component in the hierarchy if depends upon bsuch as when function calls function bor function relies on parameter that is an instance of class there are two main testing strategiestop-down and bottom-upwhich differ in the order in which components are tested top-down testing proceeds from the top to the bottom of the program hierarchy it is typically used in conjunction with stubbinga boot-strapping technique that replaces lower-level component with stuba replacement for the component that simulates the functionality of the original for exampleif function calls function to get the first line of filewhen testing we can replace with stub that returns fixed string
12,799
bottom-up testing proceeds from lower-level components to higher-level components for examplebottom-level functionswhich do not invoke other functionsare tested firstfollowed by functions that call only bottom-level functionsand so on similarly class that does not depend upon any other classes can be tested before another class that depends on the former this form of testing is usually described as unit testingas the functionality of specific component is tested in isolation of the larger software project if used properlythis strategy better isolates the cause of errors to the component being testedas lower-level components upon which it relies should have already been thoroughly tested python provides several forms of support for automated testing when functions or classes are defined in moduletesting for that module can be embedded in the same file the mechanism for doing so was described in section code that is shielded in conditional construct of the form if name =__main__ perform tests will be executed when python is invoked directly on that modulebut not when the module is imported for use in larger software project it is common to put tests in such construct to test the functionality of the functions and classes specifically defined in that module more robust support for automation of unit testing is provided by python' unittest module this framework allows the grouping of individual test cases into larger test suitesand provides support for executing those suitesand reporting or analyzing the results of those tests as software is maintainedthe act of regression testing is usedwhereby all previous tests are re-executed to ensure that changes to the software do not introduce new bugs in previously tested components debugging the simplest debugging technique consists of using print statements to track the values of variables during the execution of the program problem with this approach is that eventually the print statements need to be removed or commented outso they are not executed when the software is finally released better approach is to run the program within debuggerwhich is specialized environment for controlling and monitoring the execution of program the basic functionality provided by debugger is the insertion of breakpoints within the code when the program is executed within the debuggerit stops at each breakpoint while the program is stoppedthe current value of variables can be inspected the standard python distribution includes module named pdbwhich provides debugging support directly within the interpreter most ides for pythonsuch as idleprovide debugging environments with graphical user interfaces