id
int64
0
25.6k
text
stringlengths
0
4.59k
14,200
search trees ( ( parent null figure inserting new node into binary search tree(asearching for the node' location and (blinking the new node into the tree linkas illustrated in figure (anotice that this is the exact location where the new key needs to be inserted we can use modified version of the search operation to insert new keys into binary search treeas shown in listing to describe how the recursive method workssuppose we want to insert key value into the tree we built by hand in figure figure illustrates the method' view of the tree in each invocation and shows the changes to the tree as the specific instructions are executed remembergiven the recursive definition of binary treeeach node is itself the root of subtree as the bstinsert(recursive method navigates through listing insert key into binary tree class bstmap adds new entry to the map or replaces the value of an existing key def addselfkeyvalue )find the node containing the keyif it exists node self _bstsearchkey if the key is already in the treeupdate its value if node is not none node value value return false otherwiseadd new entry else self _root self _bstinsertself _rootkeyvalue self _size + return true helper method that inserts new itemrecursively def _bstinsertselfsubtreekeyvalue )if subtree is none subtree _bstmapnodekeyvalue elif key subtree key subtree left self _bstinsertsubtree leftkeyvalue elif key subtree key subtree right self _bstinsertsubtree rightkeyvalue return subtree
14,201
subtree subtree subtree null (abstinsert(root, (bbstinsert(subtree left,key (cbstinsert(subtree right,key subtree (dbstinsert(subtree left,key (esubtree treenode(key (fsubtree left bstinsertroot (gsubtree right bstinsert subtree subtree subtree subtree (hsubtree left bstinsert (iroot bstinsertfigure the recursive steps of the _bstinsert(method when inserting into the binary search tree each tree shows the results after performing the indicated instruction the treethe root of the current subtree will be the node of interest to insert key value the method must search for its ultimate location by recursively navigating deeper into the tree following either the left or right branch at each node as appropriate these recursive steps are shown in parts ( cof figure the gray nodes indicate the root of the subtree currently being processed by the current invocation of the method the dashed lines indicate the direction we must follow to find the correct path through the tree and then the path followed during the unwinding of the recursion
14,202
search trees the base case is reached when the empty subtree is encountered after taking the left child link from node as shown in (part dat this pointa new tree node is created and its data field set to the new key (part ea reference to this new node is then returned and the recursion begins unwinding the first step in the unwinding takes us back to node the reference returned by the recursive call is assigned to the left field of the subtree noderesulting in the new node being linked into the tree as the recursion continues unwindingshown in parts ( )the current subtree reference is returned and relinked to its parent this does not change the structure of the tree since the same references are simply being reassigned this is necessary given the way we link the new node to its parent and to allow the method to be used with an initially empty tree when inserting the first key into the treethe root reference will be null if we called the method on an empty tree with self _bstinsertself _root )the new node will be created within the methodbut the reference to the new node is not assigned to the root field and the tree remains empty since method arguments are passed by value in pythonwe have to return the reference and explicitly assign it to the root field as is done in the add(method finallyafter the new item is added to the treethe size field is incremented by one to reflect this change you may have noticed the insertion method lacks final else clause on the conditional statementwhich would handle the case when the new key equals an existing key if duplicate key is encountered during the search phasewe simply return the subtree reference to stop the recursion and allow for proper unwinding deletions removing an element from binary search tree is bit more complicated than searching for an element or inserting new element into the tree deletion involves searching for the node that contains the target key and then unlinking the node to remove it from the tree when node is removedthe remaining nodes must preserve the search tree property there are three cases to consider once the node has been located the node is leaf the node has single child the node has two children the first step in removing an element is to find the node that contains the key this can be done in manner similar to that used when searching for the location to insert new element once the node is locatedit has to be unlinked to remove it from the tree we consider the three cases separately and then provide complete listing of the recursive bstremove(method and its use in implementing the remove(method
14,203
removing leaf node removing leaf node is the easiest among the three cases suppose we want to delete key value from the binary search tree in figure after finding the nodeit has to be unlinkedwhich can be done by setting the left child field of its parentnode to noneas shown in figure (aremoving leaf node in our recursive method is as simple as returning null reference the bstremove(method uses the same technique of returning reference from each recursive call as the insertion operation by returning none back to the parent nodea null reference will be assigned to the appropriate link field in the parentthus unlinking it from the treeas shown in figure ( ( ( figure removing leaf node from binary search tree(afinding the node and unlinking it from its parentand (bthe tree after removing removing an interior node with one child if the node to be removed has single childit can be either the left or right child suppose we want to delete key value from the binary search tree in figure the node containing has subtree linked as the left child if we were to simply return none back to the parent ( as we did for leaf nodenot only would node be removedbut we would also lose all of its descendantsas illustrated in figure to remove node we will have to do something with its descendants but don' worrywe don' have to unlink each descendant and add them back to the tree since node contains single childall of its descendants will either have keys that are smaller than or all of them will be larger in additiongiven that node is the right child of node all of the descendants of node must also be larger than thuswe can set the link in the right child field of node to reference node as illustrated in figure node now becomes the right child of node and all of the descendants of node will be properly linked without losing any nodes to accomplish this removal in the recursive methodwe need only change the link in the appropriate child field of the parent to reference the child of the node
14,204
search trees figure incorrectly unlinking the interior node being deleted selecting the child field of the parent to change is automatically handled by the assignment performed upon return of the recursive call all we have to do is return the appropriate child link in the node being deleted ( ( unlinked figure removing an interior node ( with one child(aredirecting the link from the node' parent to its child subtreeand (bthe tree after removing removing an interior node with two children the most difficult case is when the node to be deleted has two children for examplesuppose we want to remove node from the binary search tree in figure node has two childrenboth of which are the roots of their own subtrees if we were to apply the same approach used with removing an interior node containing one childwhich child do we choose to replace the parent and what happens to the other child and its subtreefigure illustrates the result of replacing node with its right child this leaves the left subtree unlinked and thus removed from the tree it would be possible to link the left child and its subtree as the left child
14,205
of node but this will increase the height of the treewhich we will see later causes the tree operations to be less efficient figure attempting to remove an interior node with two children by replacing the node with one of its children the keys in binary search tree are arranged such that an inorder traversal produces sorted key sequence thuseach node has logical predecessor and successor for node its predecessor is node and its successor is node as illustrated in figure instead of attempting to replace the node with one of its two childrenwe can replace it with one of these nodesboth of which will either be leaf or an interior node with one child since we already know how to remove leaf and one-child interior nodethe one selected to replace node can then easily be removed from the tree removing an interior node with two children requires three steps find the logical successorsof the node to be deletedn copy the key from node to node remove node from the tree predecessor successor figure the logical successor and predecessor of node
14,206
search trees the latter two steps are straightforward once we have found the successorwe can simply copy the data from one node to the other in additionsince we already know how to remove leaf node or an interior node with one child we can apply the same method to remove the original node containing the successor but how do we find the successor of node and where might it be located in the treewe know the successor is the smallest key value from among those that are larger than the given node in our example treethat would be node based on the definition of the binary search treethe smallest key larger than given node is either its parent or somewhere in its right subtree since node has two childrenthe successor will be in its right subtreewhich reduces the set of nodes to be searched figure illustrates the steps when applied to our sample binary search tree since we already know how to find the minimum key in binary search tree as was implemented in bstminimum()we can use this method but apply it to the right subtree of the node being deleted this step is illustrated in figure (aafter finding the element that contains the successor keywe copy it to the node containing the element being removedas shown in figure ( ( ( ( ( figure the steps in removing key from binary search tree(afind the noden and its successors(bcopy the successor key from node to (cremove the successor key from the right subtree of and (dthe tree after removing
14,207
after copying the element containing the successor keythe node originally containing the successor has to be removed from the right subtreeas shown in figure (cthis can be done by calling the bstremove(method and passing it the root of the subtree the result of removing the successor node is illustrated in figure (dthe bstremove(method is shown in listing along with the remove(map operationwhich uses the recursive helper method to remove an entry from the tree the size field is decremented to reflect the change listing delete key from the binary search tree class bstmap removes the map entry associated with the given key def removeselfkey )assert key in self"invalid map key self _root self _bstremoveself _rootkey self _size - helper method that removes an existing item recursively def _bstremoveselfsubtreetarget )search for the item in the tree if subtree is none return subtree elif target subtree key subtree left self _bstremovesubtree lefttarget return subtree elif target subtree key subtree right self _bstremovesubtree righttarget return subtree we found the node containing the item else if subtree left is none and subtree right is none return none elif subtree left is none or subtree right is none if subtree left is not none return subtree left else return subtree right else successor self _bstminimumsubtree right subtree key successor key subtree value successor value subtree right self _bstremovesubtree rightsuccessor key return subtree efficiency of binary search trees the time-complexities for the binary search tree operations are listed in table this evaluation assumes the tree contains nodes we begin with the bstsearch(
14,208
search trees method in searching for target keythe function starts at the root node and works its way down into the tree until either the key is located or null link is encountered the worst case time for the search operation depends on the number of nodes that have to be examined in the previous we saw that the worst case time of tree traversal was linear since it visited every node in the tree when null child link is encounteredthe tree traversal backtracks to follow the other branches during searchhoweverthe function never backtracksit only moves down the treefollowing one branch or the other at each node note that the recursive function does unwind in order to return to the location in the program where it was first invokedbut during the unwinding other branches are not examined the search follows single path from the root down to the target node or to the node at which the search falls off the tree the worst case occurs when the longest path in the tree is followed in search of the target and the longest path is based on the height of the tree binary trees come in many shapes and sizes and their heights can vary butas we saw in the previous tree of size can have minimum height of roughly log when the tree is complete and maximum height of when there is one node per level if we have no knowledge about the shape of the tree and its heightwe have to assume the worst and in this case that would be tree of height thusthe time required to find key in binary search tree is (nin the worst case searching for the minimum key in binary search tree is also linear time operation even though it does not compare keysit does have to navigate through the tree by always taking the left branch starting from the root in the worst casethere will be one node per level with each node linked to its parent via the left child link the bstinsert(methodwhich implements the algorithm for inserting new element into the treeperforms search to find where the new key belongs in the tree we know from our earlier analysis the search operation requires linear time in the worst case how much work is done after locating the parent of the node that will contain the new elementthe only work done is the creation of new node and returning its link to the parentwhich can be done in constant time thusthe insertion operation requires (ntime in the worst case the bstremove(method also requires (ntimethe analysis of which is left as an exercise operation worst case bstsearch(rootko(nbstminimum(rooto(nbstinsert(rootko(nbstdelete(rootko(ntraversal (ntable time-complexities for the binary search tree operations
14,209
search tree iterators the definition of the search tree adt specifies an iterator that can be used to traverse through the keys contained in the tree the implementation of the iterators for use with the linear list structures were rather simple for the sequence typeswe were able to initialize an index variable for accessing the elements that was incremented after each iteration of the for loop with linked listthe iterator can define and use an external reference that is initialized to the head node and then advanced through the list with each iteration of the loop traversals can be performed on binary search treebut this requires recursive solution we cannot easily advance to the next key without moving down into the tree and then backing up each time leaf is encountered one solution is to have the iterator build an array of elements by recursively traversing the treewhich we can then step through as the iterator progresses just as we did with the linear structures an iterator using this approach is provided in listing while this approach worksit requires the allocation of additional storage spacewhich can be significant if the tree contains large number of elements as an alternativewe can perform recursive traversal with the use of stack rememberrecursion simulates the use of stack without having to directly perform the push and pop operations any recursive function or method can be implemented using listing an iterator for the binary search tree using an array class _bstmapiterator def __init__selfrootsize )creates the array and fills it with the keys self _thekeys arraysize self _curitem keep track of the next location in the array self _bsttraversalroot self _curitem reset the current item index def __iter__self )return self returns the next key from the array of keys def __next__self )if self _curitem lenself _thekeys key self _thekeysself _curitem self _curitem + return key else raise stopiteration performs an inorder traversal used to build the array of keys def _bsttraversalselfsubtree )if subtree is not none self _bsttraversalsubtree left self _thekeysself _curitem subtree key self _curitem + self _bsttraversalsubtree right
14,210
search trees software stack for the tree traversalnode references are pushed onto the stack as it moves down into the tree and the references are popped as the process backtracks listing shows the implementation of the iterator using software stack listing an iterator for the binary search tree using software stack class _bstmapiterator def __init__selfroot )create stack for use in traversing the tree self _thestack stack(we must traverse down to the node containing the smallest key during which each node along the path is pushed onto the stack self _traversetominnoderoot def __iter__self )return self returns the next item from the bst in key order def __next__self )if the stack is emptywe are done if self _thestack isempty(raise stopiteration else the top node on the stack contains the next key node self _thestack pop(key node key if this node has subtree rooted as the right childwe must find the node in that subtree that contains the smallest key againthe nodes along the path are pushed onto the stack if node right is not none self _traversetominnodenode right traverses down the subtree to find the node containing the smallest key during which the nodes along that path are pushed onto the stack def _traversetominnodeselfsubtree )if subtree is not none self _thestack pushsubtree self _traversetominnodesubtree left avl trees the binary search tree provides convenient structure for storing and searching data collections the efficiency of the searchinsertionand deletion operations depend on the height of the tree in the best casea binary tree of size has height of log nbut in the worst casethere is one node per levelresulting in height of thusit would be to our advantage to try to build binary search tree that has height log if we were constructing the tree from the complete set of search keysthis would be easy to accomplish the keys can be sorted in ascending order and then
14,211
using technique similar to that employed with the linked list version of the merge sortthe interior nodes can be easily identified but this requires knowing all of the keys up frontwhich is seldom the case in real applications where keys are routinely being added and removed we could rebuild the binary search tree each time new key is added or an existing one is removed but the time to accomplish this would be extreme in comparison to using simple brute-force search on one of the sequential list structures what we need is way to maintain the optimal tree height in real timeas the entries in the tree change the avl treewhich was invented by adel'son-velskii and landis in improves on the binary search tree by always guaranteeing the tree is height balancedwhich allows for more efficient operations binary tree is balanced if the heights of the left and right subtrees of every node differ by at most figure illustrates two examples of avl trees figure examples of balanced binary search trees with each node in an avl treewe associate balance factor which indicates the height difference between the left and right branch the balance factor can be one of three statesleft highwhen the left subtree is higher than the right subtree equal highwhen the two subtrees have equal height right highwhen the right subtree is higher than the left subtree the balance factors of the tree nodes in our illustrations are indicated by symbolsfor left high statefor the equal high stateand for right high state when node is out of balancewe will use either to indicate which subtree is higher the search and traversal operations are the same with an avl tree as with binary search tree the insertion and deletion operations have to be modified in order to maintain the balance property of the tree as new keys are inserted and existing ones removed by maintaining balanced treewe ensure its height never exceeds log this height is sufficient for providing (log ntime operations even in the worst case
14,212
search trees insertions inserting key into an avl tree begins with the same process used with binary search tree we search for the new key in the tree and add new node at the child link where we fall off the tree when new key is inserted into an avl treethe balance property of the tree must be maintained if the insertion of the new key causes any of the subtrees to become unbalancedthey will have to be rebalanced some insertions are simpler than others for examplesuppose we want to add key to the sample avl tree from figure (afollowing the insertion operation of the binary search treethe new key will be inserted as the right child of node as illustrated in figure (athe tree remains balanced since the insertion does not change the height of any subtreebut it does cause change in the balance factors after the key is insertedthe balance factors have to be adjusted in order to determine if any subtree is out of balance there is limited set of nodes that can be affected when new key is added this set is limited to the nodes along the path to the insertion point figure (bshows the new balance factors after key is added ( ( figure simple insertion into an avl tree(awith key insertedand (bthe new balance factors what happens if we add key to the avlthe new node is inserted as the left child of node as illustrated in figure (awhen the balance factors are recalculatedas in figure ( )we can see all of the subtrees along the path that are above node are now out of balancewhich violates the avl balance property for this examplewe can correct the imbalance by rearranging the subtree rooted at node as illustrated in figure (crotations multiple subtrees can become unbalanced after inserting new keyall of which have roots along the insertion path but only one will have to be rebalancedthe one deepest in the tree and closest to the new node after inserting the keythe balance factors are adjusted during the unwinding of the recursion the first
14,213
> < > ( ( (cfigure an insertion that causes the avl tree to become unbalanced(athe new key is inserted(bthe balance factors showing an out-of-balance treeand (cthe subtree after node is rearranged subtree encountered that is out of balance has to be rebalanced the root node of this subtree is known as the pivot node an avl subtree is rebalanced by performing rotation around the pivot node this involves rearranging the links of the pivot nodeits childrenand possibly one of its grandchildren the actual modifications depend on which descendant' subtree of the pivot node the new key was inserted into and the balance factors there are four possible casescase this caseas illustrated in figure occurs when the balance factor of the pivot node ( is left high before the insertion and the new key is inserted into the left child (cof the pivot node to rebalance the subtreethe pivot node has to be rotated right over its left child the rotation is accomplished by changing the links such that becomes the right child of and the right child of becomes the left child of > + + key key + before after figure case right rotation of the pivot node over its left child
14,214
search trees case this case involves three nodesthe pivot ( )the left child of the pivot ( )and the right child (gof for this case to occurthe balance factor of the pivot is left high before the insertion and the new key is inserted into either the right subtree of this casewhich is illustrated in figure requires two rotations node has to be rotated left over node and the pivot node has to be rotated right over its left child the link modifications required to accomplish this rotation include setting the right child of as the new left child of the pivot nodechanging the left child of to become the right child of cand setting to be the new left child of > - or key key - or key key after before figure case double rotation with the pivot' left child rotated left over its right child and the pivot rotated right over its left child cases and the third case is mirror image of the first case and the fourth case is mirror image of the second case the difference is the new key is inserted in the right subtree of the pivot node or descendant of its right subtree the two cases are illustrated in figure new balance factors when new key is inserted into the treethe balance factors of the nodes along the path from the root to the insertion point may have to be modified to reflect the insertion the balance factor of node along the path changes if the subtree into which the new node was inserted grows taller the new balance factor of node depends on its current balance factor and the subtree into which the new node was inserted the resulting balance factors are provided herecurrent factor left subtree >right subtree <modifications to the balance factors are made in reverse order as the recursion unwinds when node has left high balance and the new node is inserted into
14,215
< + key key before after < + - or - key key before or key - or key after figure cases (topand (bottomare mirror images of cases and its left child or it has right high balance and the new node is inserted into its right childthe node is out of balance and its subtree has to be rebalanced after rebalancingthe subtree will shrink by one levelwhich results in the balance factors of its ancestors remaining the same the balance factors of the ancestors will also remain the same when the balance factor changes to equal high after rotation is performedthe balance factor of the impacted nodes have to be changed to reflect the new node heights the changes required depend on which of the four cases triggered the rotation the balance factor settings in cases and depend on the balance factor of the original pivot nodes grandchild (the right child of node or the left child of node rthe new balance factors for the nodes involved in rotation are provided in table figure illustrates the construction of an avl tree by inserting the keys from the list [ ]one key at time each tree in the figure shows the results after performing the indicate operation two double rotations are required to construct the treeone after node is inserted and one after node is inserted deletions when an entry is removed from an avl treewe must ensure the balance property is maintained as with the insert operationdeletion begins by using the corre
14,216
search trees original new new new new case case case case table the new balance factors for the nodes after rotation >> (ainsert (binsert (cinsert (dleft rotate at (eright rotate at (finsert (ginsert << (hinsert (iright rotate at (jleft rotate at figure building an avl tree from the list of keys [ each tree shows the results after performing the indicated operation
14,217
sponding operation from the binary search tree after removing the targeted entrysubtrees may have to be rebalanced for examplesuppose we want to remove key from the avl tree in figure (aafter removing the leaf nodethe subtree rooted at node is out of balanceas shown in figure (ba left rotation has to be performed pivoting on node to correct the imbalanceas shown in figure ( > < ( ( (cfigure deletion that causes the avl tree to become unbalanced(athe node is located(bthe balance factors change showing an out-of-balance treeand (cthe tree after left rotation as with an insertionthe only subtrees that can become unbalanced are those along the path from the root to the original node containing the target rememberif the key being removed is in an interior nodeits successor is located and copied to the node and the successor' original node is removed in the insertion operationat most one subtree can become unbalanced after the appropriate rotation is performed on the subtreethe balance factors of the node' ancestors do not change thusit restores the height-balance property both locally at the subtree and globally for the entire tree this is not the case with deletion when subtree is rebalanced due to deletionit can cause the ancestors of the subtree to then become unbalanced this effect can ripple up all the way to the root node soall of the nodes along the path have to be evaluated and rebalanced if necessary implementation partial implementation of the map adt using balanced binary search tree is provided in listing the implementation of the non-helper methods is very similar to that of the binary search tree version since the traversal and search operations of the avl tree are identical to those of the binary search treethe valueof(method can use the bstsearch(helper method and the iter method can create an instance of the bstmapiterator of coursewe assume the implementation of these components are included within the avlmap class the
14,218
search trees listing partial implementation of the avltree py module constants for the balance factors left_high equal_high right_high - implementation of the map adt using an avl tree class avlmap def __init__self )self _root none self _size def __len__self )return self _size def __contains__selfkey )return self _bstsearchself _rootkey is not none def addselfkeyvalue )node self _bstsearchkey if node is not none node value value return false else (self _roottmpself _avlinsertself _rootkeyvalue self _size + return true def valueofselfkey )node self _bstsearchself _rootkey assert node is not none"invalid map key return node value def removeselfkey )assert key in self"invalid map key (self _roottmpself _avlremoveself _rootkey self _size - def __iter__self )return _bstmapiteratorself _root storage class for creating the avl tree node class _avlmapnode def __init__selfkeyvalue )self key key self value value self bfactor equal_high self left none self right none only change required to the add(and remove(methods is that each method must call an avl specific helper method we provide the implementation for adding new element to an avl tree and leave the removal as an exercise
14,219
the nodes in an avl tree must store their balance factor in addition to the keydataand two child links the avltreenode is provided in lines - of listing we also create and initialize three named constants to represent the three balance factor values by using named constantswe avoid possible confusion in having to remember what value represents which of the possible balance factors the implementation of the insertion operation is divided into several helper methods for better modular solution firstwe provide helper methods for performing the left and right rotationsas shown in listing right rotation on given pivot node is performed using avlrotateright(the operation is illustrated in figure the avlrotateleft(function handles left rotationas illustrated in the top of figure both methods return reference to the new root node of the subtree after the rotation listing helper functions for performing the avl tree rotations class avlmap rotates the pivot to the right around its left child def _avlrotaterightselfpivot ) pivot left pivot left right right pivot return rotates the pivot to the left around its right child def _avlrotateleftselfpivot ) pivot right pivot right left left pivot return when subtree becomes unbalancedwe have to determine which of the four possible cases caused the event cases and occur when the left subtree of the pivot node is two levels higher than the right subtreewhereas cases and occur when the right subtree becomes two levels higher than the left we divide the cases into two groups based on which subtree of the pivot node is higher the avlleftbalance(methodprovided in listing handles the rotations when the left subtree is higher to distinguish between the two caseswe have to examine the balance factor of the pivot node' left child case one occurs when the left child has factor of left high (its left child is higherfor this casethe balance factors are adjusted appropriately and right rotation is performed using the avlrightrotate(methodas shown in lines - case occurs when the balance factor of the left child of the pivot node is right high note that the case of the pivot' left child having equal balance can never occurso we do not have to check for this condition after setting the balance factorscase requires double rotationas shown in lines - we first perform left rotation on the right child (cof the pivot node the root node of the subtree resulting from this rotation becomes the new left child of the pivot node right rotation is then performed on
14,220
search trees listing helper functions used to rebalance avl subtrees class avlmap rebalance node when its left subtree is higher def _avlleftbalanceselfpivot )set to point to the left child of the pivot pivot left see if the rebalancing is due to case if bfactor =left_high pivot bfactor equal_high bfactor equal_high pivot _avlrotaterightpivot return pivot otherwisea balance from the left is due to case else change the balance factors if bfactor =left_high pivot bfactor right_high bfactor equal_high elif bfactor =equal_high pivot bfactor equal_high bfactor equal_high else bfactor =right_high pivot bfactor equal_high bfactor left_high all three cases set ' balance factor to equal high bfactor equal_high perform the double rotation pivot left _avlrotateleftl pivot _avlrotaterightpivot return pivot the pivot noderesulting in the grandchild (gof the original pivot node becoming the new root node the avlrightbalance(method can be implemented in similar fashion the actual implementation is left as an exercise the insert operation for the binary search tree returned reference to the existing subtree or the new nodedepending on the current invocation of the recursive function when inserting into an avl treethe method must also return boolean flag indicating if the subtree grew taller in order to return both valuesthe avlinsert(functionshown in listing returns tuple with the first element containing the node reference and the second containing the boolean flag finding the location of the new key and linking its node into the tree uses the same navigation technique as in the binary search tree the real difference between the insertions into bst and an avl tree occurs during the unwinding of the recursion we have to check to see if the subtree we just visited has grown taller taller child subtree means we have to check to see if the current subtree
14,221
listing inserting an entry into an avl tree class avlmap recursive method to handle the insertion into an avl tree the function returns tuple containing reference to the root of the subtree and boolean to indicate if the subtree grew taller def _avlinsertselfsubtreekeynewitem )see if we have found the insertion point if subtree is none subtree _avltreenodekeynewitem taller true is the key already in the treeelif key =subtree data return (subtreefalsesee if we need to navigate to the left elif key subtree data (subtreetaller_avlinsertsubtree leftkeynewitem if the subtree grew tallersee if it needs rebalancing if taller if subtree bfactor =left_high subtree right _avlleftbalancesubtree taller false elif subtree bfactor =equal_high subtree bfactor left_high taller true else right_high subtree bfactor equal_high taller false otherwisenavigate to the right else key subtree data (nodetaller_avlinsertsubtree rightkeynewitem if the subtree grew tallersee if it needs rebalancing if taller if subtree bfactor =left_high subtree bfactor equal_high taller false elif subtree bfactor =equal_high subtree bfactor right_high taller true else right_high subtree right _avlrightbalancesubtree taller false return the results return (subtreetalleris out of balance and needs to be rebalanced regardless if the subtree is out of balancethe balance factor of the current subtree' root node has to be modified as discussed in the previous section if subtree did not grow tallernothing needs to be done
14,222
search trees as the recursion unwindsthe growth status has to be passed back to the parent of each subtree there are only three circumstances when subtree grows taller the first is when new node is created and linked into the tree since the child link in the parent of the new node was originally nullthe new node grows from an empty subtree to subtree of height one subtree can also grow taller when its children were originally of equal height and one of the child subtrees has grown taller in all other instancesthe subtree does not grow indicating the growth of subtree is spread throughout the avlinsert(method as appropriate the - tree the binary search tree and the avl tree are not the only two tree structures that can be used when implementing abstract data types that require fast search operations the - tree is multi-way search tree that can have up to three children it provides fast operations that are easy to implement the tree gets its name from the number of keys and children each node can contain figure provides an abstract view of simple - tree figure - tree with integer search keys - tree is search tree that is always balanced and whose shape and structure is defined as followsevery node has capacity for one or two keys (and their corresponding payload)which we term key one and key two every node has capacity for up to three childrenwhich we term the leftmiddleand right child all leaf nodes are at the same level every internal node must contains two or three children if the node has one keyit must contain two childrenif it has two keysit must contain three children in additionthe - tree has search property similar to the binary search treeas illustrated in figure for each interior nodev
14,223
keys keys left subtree middle subtree keys right subtree figure search property of - tree all keys less than the first key of node are stored in the left subtree of if the node has two childrenall keys greater than the first key of node are stored in the middle subtree of if the node has three children( all keys greater than the first key of node but less than the second key are stored in the middle subtree of and ( all keys greater than the second key are stored in the right subtree the implementation of - tree assumes the nodes are constructed from the treenode class as defined in listing listing storage class for creating the - tree nodes class treenodeobject )def __init__selfkeydata )self key key self key none self data data self data none self left none self middle none self right none is this leaf nodedef isaleafself )return self left is none and self middle is none and self right is none are there two keys in this nodedef isfullself )return self key is not none does the node contain the given target keydef haskeyselftarget )if (target =self key or (self key is not none and target =self key return true else return false (listing continued
14,224
search trees listing continued returns the data associated with the target key or none def getdataselftarget )if target =self key return self data elif self key is not none and target =self key return self data else return none chooses the appropriate branch for the given target def getbranchselftarget )if target self key return self left elif self key is none return self middle elif target self key return self middle else return self right the node class contains seven fieldsone for each of the two keys and corresponding data and one for each of the three child links it also defines three accessor methods that compute information related to the given node the isleaf(method determines if the node is leafisfull(determines if the node contains two keyshaskey(determines if the target key is contained in the nodegetdata(returns the data associated with the given key or none if the key is not in the nodeand getbranch(compares target key to the nodes key(sand returns reference to the appropriate branch that must be followed to find the target these methods are included to provide meaningful names for those common operations searching searching - tree is very similar to that of binary search tree we start at the root and follow the appropriate branch based on the value of the target key the only difference is that we have to compare the target against both keys if the node contains two keysand we have to choose from among possibly three branches as in binary search treea successful search will lead to key in one of the nodes while an unsuccessful search will lead to null link that null link will always be in leaf node the reason for this is that if an interior node contains one keyit always contains two child linksone for the keys less than its key and one for the keys greater than its key in similar fashionif the node contains two keysit will always contain three child links that direct us to one of the value ranges( keys less than the node' first key( keys greater than the node' first key but less than its second keyand ( keys greater than the node' second key thusthere is never an opportunity to take null link from an interior node as there was in binary
14,225
search tree figure illustrates two searchesone that is successful and one that is not the search operation for the - tree is implemented in listing listing searching - tree class tree map def searchsubtreetarget )if we encounter null pointerthe target is not in the tree if subtree is none return none see if the node contains the key if soreturn the data elif subtree hashkeytarget return subtree getdatatarget otherwisetake the appropriate branch else branch subtree getbranchtarget return searchbranchtarget null (asuccessful search for key (bunsuccessful search for key figure searching - tree insertions the process of inserting key into - tree is similar to that of binary search treealthough it' more complicated the first step is to search for the key as if it were in the tree as we saw in the previous sectionthe search for non-existent key will lead us to leaf node the next step is to determine if there is space in the leaf for the new key if the leaf contains single keywe can easily insert the key into the node consider the partial - tree illustrated in figure and suppose we want to insert key value in searching for we end up at the node containing value since there is space in this node can be added as the node' second key but what if the new key is less than the key stored in the leaf nodesuppose we want to add key to the treeas shown in figure the search leads us to the leaf node containing value when the new key is smaller than the existing keythe new key is inserted as the first key and the existing one is moved to become the second key
14,226
search trees before ** after ** figure inserting key into - tree with space available in the leaf node before ** after ** figure inserting key into - tree with space available in the leaf node splitting leaf node things become more complicated when the leaf node is full suppose we want to insert value into our sample tree the search for the node leads to the leaf node containing keys and as shown in figure based on the search property of the - treethe new key belongs in this leaf nodebut it' full you might be tempted to create new leaf node and attach it to the full node as child this cannot be donehoweversince all leaf nodes must be at the same level and all interior nodes must have at least two children insteadthe node has to be splitresulting in new node being created at the same level before after ** ** figure inserting key into - tree with full leaf node
14,227
the splitting process involves two steps firsta new node is createdthen the new key is compared to the two keys ( and in the original node the smallest among the three is inserted into the original node and the largest is inserted into the new node the middle value is promoted to the parent along with reference to the newly created node the promoted key and reference are then inserted into the parent node figure illustrates the three possible cases when splitting leaf node and are the two keys in the original node and is the new key that we are trying to insert into the node (ax is the smallest key (bx is the middle key (cx is the largest key figure splitting leaf node into two nodeseach node gets one key and one key is promoted to the parent when key is promoted to the parentit has to be inserted into the parent' node in similar fashion to that of leaf node the difference is that reference to the newly created node is also passed up to the parent that has to be inserted into one of the link fields of the parent inserting the promoted key and reference into the parent node is simple if the parent contains single key the placement of the key and reference depends on which child node was splitas illustrated in figure (asplitting the left child kp kp kl kn km kl kn km (bsplitting the middle child kp kp kl km kn kl km kn figure inserting the promoted key and reference into parent with one key
14,228
search trees there are two cases the left child is splitthe existing key in the parent node becomes the second key and the middle child is moved to become the right child the promoted key kp becomes the first key in the parent and the reference to the new node becomes the middle child links that have to be modified are shown by directed edges in the figure the middle child is splitthe promoted key kp becomes the second key of the parent and the newly created node becomes the right child splitting parent node what happens if the node is split and its parent contains three childrenfor examplesuppose we want to insert key into the sample tree shown in figure the node containing keys and has to be split with being promoted to the parent but the parent also contains two keys ( and when the parent node is fullit has to be split in similar fashion as leaf noderesulting in key and node reference being promoted to its parentthe grandparent of the child that was split the splitting process can continue up the tree until either non-full parent node or the root is located before after ** ** figure full parent node has to be split to accommodate promoted key when the parent node is splita new parent node is created and the two will become siblings splitting full interior node is very similar to splitting leaf node two of the three keysthe two in the original parentp and and the promoted keykp have to be distributed between the two parents and one has to be promoted to the grandparent the difference is the connections between the parents and children also have to be changed the required link modifications depends on which child was split there are three casesas illustrated in figure the tree configurations on the left show the nodes and keys before the parent is split and the trees on the right show the resulting configurations the links that have to be modified are shown with directed edges splitting the root node when the root node has to be splitas illustrated in figure new root node is created into which the promoted key is stored the original root becomes the
14,229
(asplitting the left child kp kp kl kn km kl kr kn km kr (bsplitting the middle child kp kp kl km kn kl kr km kn kr (csplitting the right child kp kp kl km kr kn kl km kr kn figure inserting the promoted key and reference into full parent node left child and new child node becomes its middle child splitting the root node results in new level being added to the tree implementation the - tree insertion is best implemented recursively rememberto insert new itemnot only do we have to navigate down into the tree to find leaf nodebut we may also have to split the nodes along the path as we backtrack to the root node the implementation of the - tree insertion is provided in listing the insert(method handles the two special cases involving the root nodethe insertion of the first keyresulting in the creation of the first nodeand splitting the root noderesulting in new tree level if the tree is not initially emptythe before after figure splitting the root node is special case
14,230
search trees listing insert new key into - tree class tree map def insertselfkeynewitem )if the tree is emptya node has to be created for the first key if self _root is none self _root treenodekeynewitem otherwisefind the correct leaf and insert the key else (pkeypdatapref_ insertself _rootkeynewitem see if the node was split if pkey is not none newroot treenodepkeypdata newroot left self _root newroot middle pref self _root newroot recursive function to insert new key into the tree def recinsertsubtreekeynewitem )make sure the key is not already in the tree if subtree haskeykey return (nonenonenoneis this leaf nodeelif subtree isaleaf(return addtonodesubtreekeynewitemnone otherwiseit' an interior node else which branch do we takebranch subtree getbranchkey (pkeypdatapref_ insertbranchkeynewitem if the child was splitthe promoted key and reference have to be added to the interior node if pkey is none return (nonenonenoneelse return addtonodesubtreepkeypdatapref recursive recinsert(method is called to insert the new key this method navigates the tree to find the leaf node into which the key is to be inserted during the unwinding of the recursionthe function checks to see if the child node was splitand if it wasadds the promoted key and reference to the current interior node the addtonode()provided in listing is used to insert key into both leaf and interior nodes when the key is inserted into an interior nodethe key argument will contain the promoted key and pref will contain the promoted reference to insert new key into leaf nodethe key argument contains the new key and pref will be none if there is room for the new keythe function arranges the keys and the links in the proper order and null references are returned in
14,231
listing helper function for inserting key into node of the - tree handles the insertion of key into node if pref !nonethen the insertion is into an interior node class tree map def addtonodeselfsubtreekeydatapref )if the leaf is fullit has to be split if subtree isfull(return self splitnodesubtreekeydatanone otherwiseadd the new key in its proper order else if key subtree key subtree key subtree key subtree data subtree data subtree key key subtree data data if pref is not none if interior nodeset the links subtree right subtree middle subtree middle pref else subtree key key subtree data data if pref is not none if interior nodeset the links subtree right pref return (nonenonenonetuple to indicate the node was not split otherwisethe node has to be split by calling splitnode(and the resulting tuple is returned to the parent the splitnode()provided in listing handles the creation of the new tree node and the distribution of the keys and links to the proper location the pref argument is again used to indicate if we are working with leaf node or an interior node when an interior node is splitthe links have to be rearranged in order to maintain the tree property the three cases that can occurwhich depends on the child node into which the key is insertedare all handled by the function the promoted key and reference are returned in tuple for use by the treeinsert(function efficiency of the - tree by definitiona - tree is height balanced with all leaf nodes at the same level in the worst caseall nodes in the - tree will contain single key and all interior nodes will only have two children from the discussion of the binary search treewe know such structure results in height of log for tree of size the traversal operation must visit every node in the - tree resulting in worst case time of (nthe search operation used with - tree is identical to that of the binary search treewhich we know depends on the height of the tree since the maximum height of - tree is log nthe search operation will take no more log comparisonsresulting in worst case time of (log
14,232
search trees listing helper function that splits full node splits non-root node and returns tuple with the promoted key and ref class tree dmap if pref !nonethen an interior node is being split so the new node created in the function will also be an interior node in that casethe links of the interior node have to be set appropriately def splitnodeselfnodekeydatapref )create the new nodethe reference to which will be promoted newnode treenodenonenone see where the key belongs if key node key left pkey node key pdata node data node key key node data data newnode key node key newnode data node data if pref is not none if interior nodeset its links newnode left node middle newnode middle node right node middle pref elif key node key middle pkey key pdata data newnode key node key newnode data node data if pref is not none if interior nodeset its links newnode left pref newnode middle node right else right pkey node key pdata node data newnode key key newnode data data if pref is not none if interior nodeset its links newnode left node right newnode middle pref the second key of the original node has to be set to null node key none node data none return the promoted key and reference to the new node return (pkeypdatanewnodethe insertion operationand the deletion which we leave as an exercisealso works very similarly to that of the binary search tree the search down the tree to find leaf into which the new key can be inserted takes logarithmic time if the leaf is fullit has to be split node can be split and the keys distributed between the original nodethe new nodeand the parent node in constant time in the worst casea node split is required at each level of the tree during the unwinding
14,233
of the recursion since the tree can be no higher than log and each split is constant time operationthe worst case time of an insertion is also (log nexercises prove or explain why the bstremove(method requires (ntime in the worst case why can new keys not be inserted into the interior nodes of - tree consider the following set of values and use them to build the indicated type of tree by adding one value at time in the order listed (abinary search tree (bavl tree ( - tree repeat exercise but for the following set of keyst given the following binary treesindicate which trees are height balanced ( ( ( ( ( consider the binary search tree below and show the resulting tree after deleting each of the following keys and
14,234
search trees consider avl tree below and show the resulting tree after deleting key values and given the - tree belowshow the resulting tree after inserting key values and programming projects the binary search tree operations can also be implemented iteratively design and implement an iterative solution for each operation(asearch (bfind minimum (cinsert (ddelete design and implement the function bstmaximum()which finds and returns the maximum key value in binary search tree implement the delete operation for the avl and - trees implement the set adt using an avl search tree and evaluate the timecomplexity of each operation implement new version of the color histogram adt (from to use binary search tree for the chains instead of linked list design and implement the bstbuild(functionwhich takes sequence of keys and builds new search tree from those keys for examplethe function could be used to build the binary search tree in figure keylist [ buildbstkeylist
14,235
python review python is modern interpreted programming language that can be used to construct programs using either procedural or object-oriented paradigm it provides many built-in features and has simple syntax that is easy to learn in this appendixwe review the basics of python in order to provide refresher of the material you learned in your first introductory python course this is not complete coverage of the languagebut it focuses on those concepts that will be important to the coverage of the material in this text python has evolved over the years with various modifications and the addition of new features with each new version in this textwe assume the use of python version which includes some important differences from the popular earlier versions and in order to aide those who learned python using the earlier versionswe note the major differences throughout the review the python interpreter python programs are executed using the python interpreterwhich is program that reads and executes instructions written in the python language the interpreter can execute python programs in either interactive mode or script mode interactive mode is useful for testing single statements or small code segments to use interactive modestart the interpreter by entering the commandpython at the prompt in command-line terminal the interpreter will display an informational message similar to the followingpython ( : oct : : [gcc (red hat - )on linux type "help""copyright""creditsor "licensefor more information
14,236
appendix python review the at the bottom of the output is the interactive mode prompt that is used to enter python statements to the interpreter for exampleif you enter the statementprint"hello worldthe interpreter will respond by executing the print(function and displaying the contents of the string to the terminal windowfollowed by another promptprint"hello worldhello world script mode is used to execute python programs that are stored in text files the source files containing python programs can be created with any text editor or integrated development environment (ideof your choosing total while < total + + print"the sum of the first integers is"total to execute the programyou would change to the directory containing the file and enter the commandpython summation py at the command-line prompt this causes the python interpreter to run in script modewhich reads the text file and executes the statements contained within the file when the summation py program is executedthe following output is displayed to the terminalthe sum of the first integers is the first statement to be executed in script mode is the first statement in the text file at global scopewhich include all statements not enclosed within functionclassor method in the summation examplethe assignment statement total will be the first statement executed the basics of python programming language is defined by its syntax and semanticswhich vary from one language to the next but all languages require the use of specific instructions for expressing algorithms as program in the given language the python language consists of many different instructionsincluding those for sequentialselectionand repetition constructs in this sectionwe review the basic syntax used in the construction of simple sequential instructions
14,237
identifiers are used to name things in programming language in pythonidentifiers are case sensitive and may be of any length but they may only contain lettersdigitsor the underscoreand they may not begin with digit some identifiers are reserved and cannot be used by the programmer the following is list of python' reserved wordsand del global not with as elif if or yield assert else import pass false break except in raise none class finally is return true continue for lambda try def from nonlocal while primitive types primitive type is built-in type that is part of the language itself python defines several primitive data typesas described in the following bullets along with sample literals of each typeinteger -numeric values with no fractional part- floating-point -numeric values with fractional part - - boolean -logical values of true or falsetrue false string -an ordered sequence of alphanumeric characters'string"another string"clist -an ordered sequence of objects in which each element is identified by an integer subscript[ ['abc' [tuple -similar to list type but the contents of tuple cannot be changed once it has been created(' '' '' '( dictionary collection of items in which each item contains key and corresponding value{ "bob" "sally"python also has literal block string in which white space (spaces and newlinesis maintained """this is string which can continue onto new line when printedit will appear exactly as written between the triple quotes ""python inserts newline characters at the end of each line of the text block and adds blank spaces everywhere they appear within the literalincluding at the front of each line single or double quotes can be used for string block literals
14,238
python review statements the python syntaxas with all languagesis very specific when it comes to statement structure the interpreter expects statement to be contained on single line of the text file sometimeshoweverwe need to split single statement across several lines in order to produce easily readable code or when following the specifications of programming style guide backslash (\can be used at the end of the line to continue the statement onto the next line result (somevalue anothervalue (originalvalue for function calls and method invocations that require pairs of parenthesesthe line can be broken without the use of backslashes the interpreter will parse the instructions across lines until the closing parenthesis is encountered for examplethe following will parse without errormyfunctionab"name"avg some constructs in python are compound statementswhich span multiple lines and consist of header and statement block statement blocksometimes simply referred to as blockis group of one or more statementsall of which are indented to the same indentation levelas illustrated by the following code segmentwhile < total + + compound statements are easily identified by the requirement of colon (:as part of their syntax statement blockswhich can be nested inside other blocksbegin on the next line following the header of the compound statement statement blocks end at the next blank line or the first statement whose indentation level is shorter than those in the block only statements within block or the parts of statement continued from previous line may be indented the number of spaces used to indent statements within block is irrelevantbut all statements within the block must have the same indentation level finallythe top-level statements of file can have no indentation caution statement block indentation all statements within given block must be indented with either blank spaces or tab charactersbut not mixture of the two the alignment of statements as displayed by some text editors can be misleading it' best to use an editor that can insert "soft tabswhen the tab key is pressed
14,239
the basics of python variable terminology even though variable in python stores reference to an objectit is quite common in programming to use phrases such as "the value is assigned to ""idnum contains "and "name contains stringin all such casesthese phases should be understood as referring to the object referenced by the variable and not the variable itself variables computers manipulate and process data in pythonall data is stored in objectswhich are created from various class definitions objects can store single value or multiple values but no matter the sizewe must have some means to access the object after it' been created variable is named storage location that associates name with an object variables do not store data themselvesbut instead store references to the objects that contain the data reference is simply the memory address of the location where the object is stored assignments variables in python are created when they are first assigned an object reference consider the following assignment statementsname "john smithidnum avg which creates three variables and assigns references to each of the given literal values note that reference to an object is commonly illustrated as directed edge leading from the variable to the objectidnum avg name "john "john smithsmithin pythonobjects are automatically created for literals and initialized with the given value each unique literal within program results in unique object variable itself does not have type and thus can store reference to any type of object it is the objectthat has data type variable cannot be used before it has been created by an assignment of reference to some object attempting to do so will generate an error as shown in the previous code segmentpython uses single equal sign (=for assigning an object reference to variable when an assignment statement is usedthe righthand side is evaluated and reference to the resulting value is stored in the variable on the lefthand side when new reference is assigned to an existing variablethe old reference is replaced for examplesuppose we assign new value to variable idnum using the assignment statement idnum which results in the original reference to value being replaced by reference to value idnum avg name "john "john smithsmith
14,240
appendix python review if all references to an object are removed--that isno variable contains reference to the object--it is automatically destroyed as part of python' garbage collection idnum avg name "john "john smithsmithaliases when one variable is assigned to another (student name)the reference contained in the variable on the righthand side is copied to the variable on the lefthand sideresulting in an alias since both variables refer to the same objectidnum avg student name "john "john smithsmithnull references variable can be set such that it does not reference any objectin which case it' called null reference in pythonthe special object none is used to set null reference for examplesuppose we execute the assignment statement idnum noneafter which idnum will be null referenceas shown hereidnum avg name student "john "john smithsmithconstants some languages support the creation of constant variables constant variableor simply constantis variable whose value cannot be changed after it has been assigned an initial value python does not support constant variablesbut it is common practice to specify constant variables with all capital lettersas illustrated in the following exampletax_rate max_size it is important to notehoweverthat there is no way to enforce the concept of constant variable and keep its value from being changed but by following the standard conventionyou provide information to yourself and others that you intend for variable in all caps to be constant throughout the program arithmetic operators python supports the common mathematical operations for both integers and realsaddition subtraction multiplication real division /*floor division modulo operator power
14,241
the numeric type resulting from an arithmetic operation depends on the type of the two operands if at least one operand is floating-pointthe result will be floating-point and if both operands are integersthe result will be an integer an exception is the real division operator (/)which always returns floating-point the floor division operator (//mathematically computes ba/bc but returns an integer if both operands are integers and floating-point if at least one is floatingpoint the modulo operator (%returns the remainder left after computing floor division the operators have the expected order of precedence as found in mathematics but can be overridden using parentheses all of the operatorsexcept the power operator (**)are evaluated from left to right special care must be taken when using the power operator with negative literal values negative literal on the left side of the power operator is treated differently than one on the right side for examplethe python expression - * is evaluated as -( * while the expression *- is evaluated as *(- python also supports the compound assignment operators that combine an assignment with an arithmetic operator+-*/%**//these operators perform the arithmetic operation on both operands and store the result back in the variable on the lefthand side for examplethe expression + is equivalent to the arithmetic new in python xthe functionality of the division operator (/has changed it now performs real division and returns floating-point value even if both operands are integers the floor division operator (//has to be used for integer division logical expressions decisions in programming language are made based on the boolean result (true or falseof logical expression logical expressions are constructed using logical operatorswhich can be divided into two groupsrelational operators and boolean operators relational operators the relational operators are used to determine if given relationship exists between pairs of values for examplewe may want to determine if student has failing grade where failing is any average below the logical expression for that evaluation would be written asavg > the result of which is either true or false the relational operators can be used with any of the built-in types the numeric values are compared by relative mag
14,242
appendix python review nitude while strings are compared lexicographicallycharacter by character from left to right the python relational operators are shown herea = is greater than is less than is equal to > < ! is greater than or equal to is less than or equal to is not equal to boolean operators the boolean operators are applied to boolean values they allow for the construction of not only boolean expressions but also more complex logical expressions by combining multiple relational and boolean expressions for exampleconsider the following logical expressionavg > and avg < which determines if the given value is in the range [ the python boolean operators are described nextnot and or unary operator that inverts the boolean value of its operand true if and only if both and are true true if is trueb is trueor both and are true the logical operators are evaluated from left to right based on their order of precedence which can be overridden using parentheses the relational operators have the highest precedence followed by the boolean operators in the order listed new in python xthe operatorwhich in earlier versions could be used in place of !=is no longer available object references python provides the is and is not operators for comparing referencesor the addresses stored in variables for examplein the code segmentname "smithname "jonesresult name is name result is set to false since the two variables point to two different objects if we modify the segment as followsname name result name is name result is now set to true since the two variables refer to the same object and are thus aliases the is not operator returns the inverse of the is operator and is equivalent to applying the boolean not operator for examplethe following logical expressions are equivalent
14,243
result name is not name result not (name is name we test for null reference with the use of the special value none result name is none result name is not none using functions and methods while python is an object-oriented languageit provides both class structure for object-oriented programming and function structure for procedural programming function is stand-alone group of statementssometimes called subprogramthat performs specific task function is used by invoking it via function call for exampley absx computes the absolute value of variable and stores the result in when function is called during executionthe flow of execution jumps to the functionexecutes its instructionsand then returns to the point where the function was called function call consists of the function name and an argument list enclosed within parenthesesfuncarg arg argn arguments are simply values that are passed to the function for use by that function the number of arguments passed to function depends on the specific function when multiple arguments are passed to functionthey are separated with commas and passed in the order specified by the function header if function requires no argumentsthe parentheses are still required some functions may return value this value can be used or ignored depending on the purpose of the function if function returns valuethe function call can be used anywhere value of the given type can be used for examplesince the abs(function returns numeric valueit can be used as part of an arithmetic expressiony absx as indicated earlierall values in python are stored in objects that are created or instantiated from classes once an object has been createdit can then be used objects are automatically instantiated or created for all literal values within program but we can also explicitly create objects by calling the constructor of the corresponding class for the given type of object for examplewe can create string object by calling the constructor of the str classname str"jane green
14,244
appendix python review as you are probably guessingthere is no need to use the str(constructor explicitly to create string object since we can just specify literal string in our code and have the interpreter automatically create an object for us but the str(constructor can also be used to create string representations of other data typesboth literal values and those referenced by variablesx intstr strx floatstr str boolstr strfalse ' ' 'falsesince python' built-in types are represented as classesthey each have constructor that can be used for creating objects of the given type the following is list of the constructors for the simple typesintx floatx integer floating-point boolx strx boolean string these constructors can also be used to convert between the various types for examplewe can convert the string representation of numeric value to the given numeric type using the appropriate constructori int" float' operations can be performed on objects by invoking method defined for the class of the given type we have already seen the arithmetic operators used with the numeric types but methods can also be defined for use with objects the dot operator is used to apply method to given object for examplewe can create new string that is the lowercase version of an existing string using the lower(method defined by the str classname "jane greennewstr name lower( method is very similar to function with one major difference function is stand-alone subroutine that can be used independent of an objectwhereas method is defined by class and must be applied to an object of that class standard library python is relatively small language but provides the necessary components for creating powerful programs the built-in typeswhich are part of the language itselfhave class definitions defined directly by the language in additionthere are number of built-in functions such as print()input()and abs()that are also provided directly by the language additional functionality is available from various components in the python standard library the standard library contains number of functions and class definitions in which related components are organized into individual files called modules while built-in functions and methods can be used directly within your programthose
14,245
defined within module must be explicitly included in your program to use function or class from the standard libraryyou include an import statement at the top of your program for exampleto use function defined in the standard math moduleyou would include the statementfrom math import at the top of your program file the import statement loads the contents of the named module and makes all definitions within single module available for use in your python program for exampleafter importing the math modulewe can use the sqrt(functionwhich is defined in the moduley sqrtx you can import individual components of module and make them available within the current file usingfrom math import sqrt which includes the modulebut only makes the sqrt(function available for use in your program python has second variation to the import statement that works very much like the from/import versionimport math but in this casethe components defined in the module are loaded into their own namespace namespaces will be discussed in more detail later in this appendix for nowsimply note that after using this form of the import statementthe included components have to be referred to by both module name and component name and separated by doty math sqrtx user interaction user interaction is very common in computer programs in gui (graphical user interface)-based programsthe interaction is managed through widgets or controls displayed within windowed environment in text-based programsuser input originates from the keyboard and output is written to the terminal standard input in pythonthere is single function for extracting data from the user via the keyboard the input(function waits for the user to type sequence of characters followed by the enter key name input"what is your name
14,246
appendix python review the string argument passed to the input(function is user promptwhich tells the user what information we are looking for when the previous statement is executedthe python interpreter will display the string on new line in the terminal followed by the cursorwhat is your nameand then it waits for the user to enter data after the user enters sequence of characters and presses enter the data is returned as string and assigned to the variable namewhich can then be used within the program the input(function can only extract strings but what if we need to extract an integer or real valuein that casethe numeric value will be extracted as string of digits that must be converted to numeric value using the appropriate numeric type constructor in the following exampleuserinput input"what is your gpagpa floatuserinput we extract floating-point value from the user by passing the input string to the float constructorwhich converts the numeric string representation to real value this code segment can be written by nesting the two function callsgpa floatinput("what is your gpa?"new in python xin previous versions of pythonthere were two functions for extracting data from the userinput(and raw input(the input(function has been changed to provide the functionality of raw input(and raw input(has been removed from the language standard output in pythonas you have seen in number of examplesthe print(function is used to display information to the terminal when the following is executedprint"hello world!!the string is displayed in the terminal followed by line feedwhich moves the cursor to the next line the print(function can only output strings but python will implicitly convert any of the built-in types to strings using the str(constructor for examplewhen the following code segment is executedavg (exam exam exam print"your average isprintavg the floating-point value stored in avg will be converted to string and displayed to the terminal the result isyour average is
14,247
new in python xthe print statement has been changed to function and now requires parentheses in additionkeyword arguments have been added to the function for changing the default behavior multiple arguments can be supplied to the print(function in that caseeach argument is printed one after the other separated by single blank spaceprint"your average is"avg which produces as outputyour average is the default behavior of the print(function produces line feed after the last argument is printed this can be suppressed by including the keyword argument end to the argument list for examplethe following code segmentprint"your average is"end printavg produces as outputyour average is because the first call to the print(function does not produce line feed after the string is printed since it was suppressed by including the keyword argument end '\nthe default value for the argument is end '\ 'which produces line feed after the last argument escape sequences escape sequences are used in python to represent or encode special characters such as newlinestabsand even the quote characters an escape sequence is two-character sequence consisting of backslash (\followed by letter or symbol consider the following exampleprint"start newline here \nusing the \\ character which producesstart newline here using the \ character the common escape sequences are shown here\\backslash (\single quote ('\ \ newline horizontal tab \double quote ("
14,248
appendix python review formatted output python overloads the modulus operator (%for use with strings to produce formatted output consider the following exampleoutput "your average is % favggrade printoutput which creates new string using the format string from the left side of the operator and replacing the field format specifier (% fwith the value of the avggrade variable the resulting string is then printed to standard outputyour average is it is common to nest the formatted string operation within the print(function when used to produce standard outputprint"your average is % favggrade more than one field format specifier can be used in the format definition in this casethe replacement values must be provided as tupleprint"origin(% % )\ (pointxpointythe replacement values are associated with the field format specifiers in the order listed and must be of the appropriate type the following code segment shows the use of the formatted output to produce report containing dollar amounts aligned on the decimal pointprint"wages% fwages print"state taxes% fstatetaxes print"fed taxes% ffedtaxes print"pay% ftakehome there are different field format specifiers for the various primitive data types and several optional arguments that can be used to tweak the output field format specifier has the general structure%[flags][width]precision]code flags -indicates zero fills or optional justification and is one of the following fill preceding blank spaces within the field with zeroes right-justify the value within the field left-justify the value within the field width -is an integer value indicating the number of spaces in the field used when formatting the replacement value precision -is the number of digits to be printed after the decimal place when printing floating-point value
14,249
code -indicates the type of data that is to replace the field specifier it can be one of the following% % % % % % % string decimal or integer same as % floating-point character unsigned integer octal integer % % % % % % %hexadecimal integer same as % but uppercase scientific notation uppercase version of % same as % uppercase version of % prints literal control structures to this pointwe have reviewed statements that are executed in sequenceone after the other sometimeshoweverit may be necessary to change the flow of control and only execute statement or block of statements if some condition is met or to execute the same statement or block of statements multiple times selection constructs selection statements allow you to choose whether to execute statement or block of statements based on the result of logical expression python provides several forms of the if construct for making decisions and selecting certain statements for execution the if construct can take several forms the if-then form is used to select statement or block of statements if and only if some condition is met consider the following exampleif value print"the value is negative in which the print(function is executed if value is negativeotherwisethe statement is skipped the if-else statement the if-else form of the if construct is used to execute block of statements if condition is true and different block of statements if the condition is false this form is identified by the inclusion of an else clause in the following exampleif value print"the value is negative elseprint"the value is positive value is tested to determine if it is negative or positive and an appropriate message is displayed
14,250
appendix python review nested if statements there is no restriction on the type of statements that can be included within the blocks executed by the if statement sometimesit may be necessary to nest an if statement within another if statementif num num if num num smallest num elsesmallest num elseif num num smallest num elsesmallest num the if statement and its corresponding else clause must be aligned properly to produce the correct result in the following examplethe else clause must be aligned with the second if statement to produce the message "passing but marginalwhen the average grade is in the range [ if avg if avg print"failingelse print"passing but marginal if the else were aligned with the first if statementas shown belowthe message would be incorrectly printed for averages greater than or equal to if avg if avg print"failingelse print"passing but marginal multiway branching special form of the if construct can be used with selections that tests series of conditions and performs an action for the one which results in true for examplesuppose we need to determine the letter grade to be assigned for given average using the common ten-point scale this can be accomplished using series of nested if statements as shown below on the left
14,251
if avggrade > lettergrade "aelse if avggrade > lettergrade "belse if avggrade > lettergrade "celse if avggrade > lettergrade "delselettergrade "fif avggrade > lettergrade "aelif avggrade > lettergrade "belif avggrade > lettergrade "celif avggrade > lettergrade "delselettergrade "fbut as more and more conditions are nestedthe structure becomes more complex and the blocks continue to be indented further and furtherwhich can make it difficult to read the code python provides third form of the if construct that can be used to implement series of conditions or multiway branchesas shown above on the right the else part can be omitted if there is no default part to the multiway branch the ifelifand else clauses must be aligned to the same indentation level repetition constructs there are many occasions when we need to execute one or more statements multiple times until some condition is met for examplesuppose we want to compute the wages for number of employees given the number of hours each worked while the wage computation is the same for each employeeit is has to be performed for multiple employees thuswe can have the computer repeat the data extraction and computation for each employee until the data has been processed for all employees python has two repetition constructswhile and for the while loop loops can generally be categorized as either count-controlled or event-controlled in count-controlled loop the body of the loop is executed given number of times based on values known before the loop is executed the first time with eventcontrolled loopsthe body is executed until some event occurs the number of iterations cannot be determined until the program is executed the while loop is general looping construct that can be used for many types of loops consider the following count-controlled loopwhich sums the first integers by repeatedly executing the body of the loop timesthesum initialization while < condition thesum + + modification print"the sum ="thesum
14,252
appendix python review the while loopwhich is compound statementconsists of two partsa condition and loop body the body of the loop contains one or more statements that are executed for each iteration of the loop the number of iterations is determined by the conditionwhich is constructed using logical expression the body of the while loop is executed while the condition is true since logical expressions are constructed by comparing and examining the values of one or more variablesthe variables must be altered in order to change the condition thusevery loop must contain an initialization and modification component the initialization is performed before the condition is examined and the body is executed it is used to initialize the loop variable upon which the loop condition is based at some point within the loop bodythe loop variable must be modified so the loop condition can change as an example of an event-controlled loopconsider the problem of entering multiple exam grades from the user and then computing the average grade we need to enter multiple grades but we don' know how many will be entered to accommodate this unknownwe can repeatedly execute the body of the loop until the user enters special valueknown as the sentinel value in the following solution for this problemthe sentinel value is any negative number the event of entering the special value terminates the loopthus leading to the name eventcontrolled loop total count value intinput("enter the first grade"while value > total +value count + value intinput("enter the next grade (or to quit)"avg total count print"the average grade is % favg python also provides the break and continue jump statements for use in loops the break statement is used to break out of or terminate the innermost loop in which it is used the continue statement immediately jumps back to the top of the loop and starts the next iteration from the point of the condition evaluation when using real values (floatswith logical expressionsyou may get results you do not expect due to the imprecision of real number arithmetic on computers consider the following code segmenttotal while total + + if total = print"correctelse print"not correct
14,253
which adds the fractional value ten times to variable total since total has an initial value of mathematicallyit should equal after the loop terminates and the program should print the string "correctbut due to the imprecision of floating-point numberstotal contains value close to but not equal to and thus the program will print the string "not correctthe for loop the for statement in python is part of the built-in iterator mechanism used to traverse the individual items stored in sequence or collection the individual items in the given collection are assignedone at timeto the loop variable after each assignmentthe body of the loop is executed in which the loop variable is commonly used to perform some action on each item the loop body will be executed once for each item in the collection consider the following code segmentcount for letter in thestring if letter >"aand letter <"zcount + print"the string contained % uppercase characters count which traverses over the individual characters of the string "john smith"one at timeto count the number of uppercase letters contained in the string python' for statement is equivalent to the foreach constructs found in other languages thuswhen reading code containing for loopit' best to read the "forclause as "for eachconsider the loop in the previous code segmentwhich we would read as "for each letter in thestring do the followingwhere "do the followingrepresents the statements in the loop body python also provides the range(functionwhich can be used with the for statement to construct count-controlled loops consider the following code segmentwhich prints the range of integers from to one per linefor in range printi the range(function specifies sequence of integer values over which the for loop can traverse there are several forms of the range(function depending on the number of arguments supplied consider the following examplesthird argument indicates the increment amountdefault is for in range printi we can decrement through the range of values for in range - printi single argument will iterate through the rangestarting at for in range printi
14,254
appendix python review collections python provides several data types that can be used to store and manage data collectionsthe stringtuplelist and dictionary strings python also provides several built-in collection classes strings are very common and fundamental in most programming languages in pythonstrings are immutable objects of the built-in str classwhich store the sequence of characters comprising the string number of basic operations can be performed on stringssome of which are described in this section two strings can be concatenated using the plus operator for examplestrvar 'this is fullstr strvar " stringresults in the string "this is stringbeing assigned to variable fullstr to concatenate string with non-string valueyou must first create string representation of the non-string using the str(constructorresult "the value of is strx python provides the built-in len(function that can be applied to any of the built-in collections when used with stringit returns the number of characters contained in the string print"length of the string "len(namein an earlier sectionwe saw that the individual characters of string can be accessed by traversing the sequence using an iterator an individual character of string can also be accessed by specifying an integer subscript or index representing its position within the string consider the following examplewhich prints the first and last character of stringmsg "this is string!print"the first character is"msg[ print"the last character is"msg[- both positive and negative subscripts can be used positive subscript represents the offset of the character from the front of the string while negative subscript indicates the offset from the end of the stringas illustrated herename - - - - - - - - - - the subscript must be within the valid range for the given stringotherwisean exception will be raisedresulting in an error printing dashed line is common operation in text-based applications one way to do it is as string literal
14,255
print"but python provides string repeat operator for duplicating or repeating string that produces the same resultsprint"- lists python list is built-in collection type that stores an ordered sequence of object references in which the individual items can be accessed by subscript list can be created and filled using comma-separated sequence within square brackets for examplethe first statement in the code segmentgradelist lista [two empty lists listb list(creates five-element list containing the specified integers and stores reference to the list in the gradelist variable the resulting gradelist is illustrated heregradelist element access list elements are referenced using the same square bracket subscript notationused with strings as with stringsthe elements are numbered in sequential orderwith the first element having index zero negative subscripts can also be used to reference the elements starting from the end print'first item 'gradelist[ print'last item 'gradelist[- list can be printed using the print(functionas can most python data typesor it can be converted to string consider the following code segmentastring strgradelist printgradelist which produces the following output [ the elements of list can also be accessed by traversing the list using the iterator mechanismfor element in gradelist printelement
14,256
appendix python review list modification the contents of specific element of the list can be modified using the subscript notation with the variable name on the left side of an assignment statement for examplethe following code segment replaces grade with gradelist[ printgradelist prints [ new items can be appended to the end of the list using the append(method the following code segment creates list of , random values by appending each value to the end of an initially empty listimport random valuelist list(for in range valuelist appendrandom random(the extend(methodwhich takes list as its argumentcan be used to append multiple items to the end of list for examplethe following code segmentlista listb lista extend printlistb produces as output [ the entire contents of the argument are appended to the end of the list for which the method was invoked the insert(list method can be used to insert items anywhere within list consider the codevalues values insert printvalues which produces the output [ the insert(method inserted value before the current item at position the remaining items were shifted down to make room for the new item python provides several methods for deleting items from list the first approach uses the remove(methodwhich allows you to delete an item by valuethelist thelist remove printthelist prints [ printlen(thelistprints to remove an item by indexyou can use the pop(methodwhich retrieves and then removes the item at the given index in the following code segmentwe use the pop( method to retrieve and remove the item at index position thelist pop print"list ="thelist print" =" prints list [ prints
14,257
the items following the removed item are shifted down and the size of the list shrinks by one you can omit the index position for pop(and the item in the last element will be retrieved and removed thelist pop(printthelist prints [ searching the list several methods and operators are provided that can be used to search the list the index(method can be used to search for an item within the list it returns the element index of the first occurrence within the list if the list does not contain the given valuean exception is raised thelist pos thelist index printpos prints tuples another built-in collection type for creating an ordered sequence of objects is the tuple tuples are exactly like listsexcept they are immutable tuple is created using pair of parentheses instead of square brackets 'abc' element tuple element tuple element mixed tuple you have already seen the use of tuples when multiple values were passed as data fields in formatted string that were listed within parenthesesas shown below that was actually tuple many of the operators used with lists can also be used with tuplesbut there are no additional methods defined for tuples print"(% % )(xya dictionaries the python dictionary is built-in class that stores collection of entries in which each entry contains key and corresponding valuesometimes called payload dictionary can be created and filled using sequence of comma-separated key:value pairs listed within curly braces or empty dictionaries can be created using empty bracesor the dict(constructorstates 'ms'mississippi''va'virginia''al'alabama''dc'washingtonclasslevel 'freshman' 'sophomore' 'junior' 'senioremptya emptyb dict(
14,258
appendix python review element access the items stored in dictionary are accessed based on the key part of the key/value pair accessing an entry in the dictionary also uses the subscript notationbut unlike list or tuplethe subscript value is one of the keys in the dictionary print'the state name is'states['ms'when using the subscript notation to access an entry in the dictionarythe given key must exist or an exception is raised as an alternativethe get(method can be usedwhich returns the value associated with the given key if it exists or returns none if the key does not existprintstates get'msprintstates get'mdprints mississippi prints none the collection can be traversed using python' iterator mechanism provided through the for statement the traversal is made over the keys in the dictionary to access the corresponding valuesimply use the subscript notation for key in classlevel printkey'='classlevel[keyyou can obtain list of the keys or values stored in the dictionary using the appropriate methodkeylist states keys(valuelist states values(dictionary modification the value associated with key in the dictionary can be changed using the dictionary subscript notation with the variable name on the right side of an assignment statement for examplethe following code segment corrects the entry for dc in the states dictionary and then prints the contents of the dictionarystates['dc''district of columbiaprintstates which results in{'va''virginia''al''alabama''ms''mississippi''dc''district of columbia'new entries can also be added to dictionary using the dictionary subscript notation thusif the key existsits corresponding value is modifiedif the key does not exista new key/value pair is added to the dictionarystates['or''oregonstates['vt''vermontprintlen(statesprints
14,259
an existing entry can be removed from dictionary using the pop(method or the del operator the given key must exist in the dictionarystates pop'aldel states['vt'the in and not in operators can be used to determine if dictionary contains given key these can also be used with stringstuplesand lists if abbv not in states printabbv"is not valid state abbreviationif in gradelist print"student received at least one perfect score text files data files stored on secondary device such as hard drive or usb stick can be used for the input of data into program and the output of data from program for exampleif we want to produce and print reportwe need we need to write the information to file and then print the file the data needed to produce that report may itself be stored in file on disk we would have to extract the data from the fileprocess itand then produce the report in most languagesfiles are treated as / streams (input/output streamsin which data flows into or out of program internallystandard inputin which data is extracted from the keyboardis treated as an input stream and standard outputin which data is written to the terminalis treated as an output stream there are two main types of data files that can be used with pythontext files and binary files text file contains sequence of characters from the printable range of the ascii code this typically includes the ascii values in the range [ and ascii values and which are used for newlines and tabs examples of text files include those created by any text editor such as the source files containing your python programs binary file contains sequence of binary numbers representing data values as they would be stored in memory examples of binary files include those created by word processorsspreadsheet applicationsand databases binary files cannot be read and displayed by text editors since they contain byte values outside the printable range in this sectionwe limit our discussion to text files since they are very common and easy to work with file access files are built-in type in python that are represented by objects this means no additional modules are required in order to access file from within your program before file can be usedit must first be opened and an object created to represent the file text file is opened using the open(functioninfile open"records txt""routfile open"report txt""
14,260
appendix python review the function takes two string arguments the first is the name of the file and the second indicates the mode in which the file is to be opened the modes are' ' -open the file for reading -open the file for writing new in python xpython now includes multiple classes for working with files the file(constructor no longer exists and cannot be used to open file insteadyou must use the open(functionwhich creates and returns an appropriate file object based on the supplied arguments if the file can be openedthe function creates file object and returns reference to that newly created object this object is then used to access the file file opened for reading must exist and be accessible to the user running the program if file is opened for writing and it does not exista new file is createdbut if the file existsit will be erased and new file created if the file cannot be openedan error is generated when you are finished using the fileit should be closed by closing the filethe system will flush the buffers and unlink the external file from the internal python object file cannot be used after it has been closed to reuse the fileyou must first reopen it python files are closed by calling the close(method defined for file objectsinfile close(outfile close( writing to files python provides several methods for outputting data to text file the easiest way to write text to text file is with the write(method defined for file objectsoutfile write"student report\noutfile write"- "\nthe write(method writes the given string to the output file represented by the given file object to output other value typesyou must first convert them to strings formatted output can also be written to file using the string format operatoroutfile write"% % \ (idnumavggradenote that the write(method does not add linefeed or newline character after the string is written to the file this must be done explicitly by including newline character (\nas part of the output string
14,261
reading from files python provides two methods for extracting data from text fileboth of which extract data as strings to extract other types of data from text fileyou must explicitly convert the extracted string(sas was done with the input(function the readline(method is used to extract an entire line from text file the end of line is indicated by newline character (\nthe extracted text is returned as stringline infile readline(if the file is empty or the end of file has been reachedthe readline(method returns an empty string (""to flag this resultinfile open"data txt""rline infile readline(while line !"printline line infile readline(infile close(the readline(method leaves the newline character at the end of the string when the line is extracted from the file the rstrip(string method can be used to strip the white space from the endline infile readline(stripped line rstrip(to read individual characters from text filesimply pass an integer value to the readline(method indicating the number of characters to be extractedch infile readline read single character python provides the readlines(method that can be used to extract the entire contents of an open file and store it into string listlines infile readlines(an alternate approach to processing the entire contents of text file is with the use of the file iterator consider the following examplewhich extracts the input fileone line at timeand then writes it to the output fileinfile open"myreport txt""rfor line in infileprintline infile close(the previous examples dealt with the extraction of strings from text file but what if we need to extract numeric valuessince python only provides methods for extracting stringswe must handle the conversions explicitly consider the following sample text file containing three pieces of information for student
14,262
appendix python review smithjohn the first line is an integer identification numberthe second is the name of the student stored as text stringand the last line is the student' average computed as floating-point value to extract the informationeach line must be read as string and the two numeric values must be explicitly converted to the appropriate numeric type idnum intinfile readline(name (infile readline()rstrip(avg floatinfile readline(typicallythe newline character should be removed from strings that are part of data records otherwiseproblems can occur when processing the stringsas would be the case when performing string comparison the removal of the newline character can be combined with the extraction as shown in the above code segmentor performed as two separate operations user-defined functions python allows users to define their own functions that can be used like any other built-in or library function functions allow for the subdivision of larger problems into smaller parts and for the reuse of code in this sectionwe review the creation and use of user-defined functions the function definition python function contains header and body the function header is specified using the def keyword while the function body is given as statement block the header consists of name by which the function can be called and parenthesized comma-separated list of formal parameters consider the following code segmentdef sumrangefirstlast )total first while <last total total return total that defines the function sumrange()which requires two arguments the function sums the range of values specified by the first and last numeric arguments and returns the result user-defined function is called like any other function in pythonas illustrated in the following code segmentthesum sumrange print"the sum of the first integers is"thesum
14,263
function arguments when function is calledthe flow of execution jumps to the function the arguments specified in the function call are copied to the function parameters in the order specified the function is then executed beginning with the first statement in the function body when return statement is executed or the end of the function body is reachedexecution returns to the point where the function was called in pythonarguments are passed by value since every value is an objectit is the object reference that is copied to function parameter and not the object itself for examplesuppose we call sumrange(with two variablesstart end thesum sumrangestartend inside the functionvariables first and last are local variables that contain aliases to variables start and endrespectively start end sumrangestartend first last the local scope for this method invocation python is dynamically typed language and every operator in python is polymorphic operation sowhat keeps us from passing floating-point values into the sumrange(functionfor examplethe function call sumrange( would be valid so long as all operations within the function can be applied to the given valuesthe program will execute correctly if an operation cannot be applied to given argument typean exception will be raised to indicate the invalid type this flexibility is powerful feature of python it allows single function to be applied to different object types without having to define multiple versions returning values as indicated earlierthe return statement can be used to terminate functionbut it' also used to return valueor more specifically an object referenceback to the program where the function was called for examplethe sumrange(function returns the total that results from summing the range of values using the statement return total most value-returning functions return single value but python does not limit you to only returning single value multiple values can be returned by specifying comma-separated list as part of the return statement for examplethe following function prompts the user for their first and last names and then returns both stringsdef promptforname()first input"what is your first name
14,264
appendix python review last input"what is your last namereturn firstlast function that returns multiple values can only be called as part of multivariable assignment statementfirstnamelastname promptforrange(the multiple values returned by function are assigned to the variables in the order they are listed in the return statement thusif we execute the above function call and enter data as followswhat is your first namejohn what is your last namesmith the string 'johnwill be assigned to firstname and 'smithwill be assigned to lastname note that when multiple values are returned by functionpython actually returns tuple with the values stored as elements thussome books will show the assignment of the returned values using the following equivalent notation(firstnamelastnamepromptforrange(default and keyword arguments python allows functions to be defined with default argument values for examplewe can add third parameter to the sumrange(function to be used as the step value and assign default value to the argumentdef sumrangefirstlaststep )total first while <last total total step return total if the value of the third argument is omitted when calling the functionthesum sumrange the default value is assigned to the parameter before the function is executed if value is specified in the function call for the third argumentthesum sumrange then that value is used instead of the default value when defining functions with default argumentsall arguments following the first one with default valuemust be assigned default values otherwisepython would have no way of knowing which argument is supposed to receive the default value the arguments specified in function call are passed to the parameters of function in the order they were specified python also allows you to specify the argument order by using keyword arguments consider the following function call
14,265
thesum sumrangelast step first in which we directly specify which argument is supposed to receive which value as we've seen earlierkeyword arguments can be used with the print(function to change the separation string that gets inserted when printing multiple arguments and to change the string printed at the end of the function call variable scope variables are classified by their scopewhich indicates where the variable was created and where it can be used python has four scope classifications the built-in scope includes the variables and literal values defined as part of the languagewhich can be used anywhere within program the global scope includes the variables created at the top level of source file or module (outside of all functions and classesunlike other languages in which global variable can be used anywhere within programeach module in python creates its own global scope the local scope includes the variables created within function or method and are local to the given subroutine function and method arguments are local variables and finallythe instance scope includes the variables defined as data attributes of class these will be discussed more in appendix variables only exist within the scope in which they were created the builtin and global scopes exist during the entire life of the program variables in the instance scope exist during the lifetime of the object for which they were defined local variablehoweveronly exists during the time in which the function is being executed each execution of function creates new local scopewhich is then destroyed when the function terminates main routine every program must have unique starting pointa first statement to be executed in pythonthe first statement to be executed is the first statement at file level (outside of all functions and class definitionsthe statements within function are not executed until the function is calledeven though the statements are interpreted and converted to byte code as they are read thusyou can refer to one function from within another before the former has been defined for exampleconsider the following code segmentdef run()value intinput("enter value"print"the double of your value is "doubleitvalue def doubleitnum )return num run(but this is not the case when calling function from statement at file level when python source file or module is loaded by the interpreterall statements at
14,266
note python review use of main routine in the textwe only use main(function when the driver module contains multiple functions as illustrated by the diceroll py program below if the driver module does not contain multiple functionsas illustrated by the driver py modulewe omit the main(function and list all executable statements at the file level file level are executed during the loading process if function is called at file level before the function has been definedas illustrated in the following code segmentthe interpreter does not know about the function and has no way of executing itcallit def callitnum )return pownum the order in which functions are listed within file is not importantbut the order of executable statements at file level is when subdividing program into various functions using top-down designit is good programming practice to place all executable statements within functions and to specify one function as the driveras illustrated in the following code segment with this approachthe driver functionwhich is commonly named main(due to that name being used in other languagescan be defined first with the remaining definitions following it at the bottom of the filea single file-level statement (not including constant variablesis used to call the driver function diceroll py simulate the rolling of two dice from random import minimum number of sides on die min_sides our very own main routine for top-down design def main()print"dice roll simulation numsides intinput("how many sides should the die have"if numsides min_sides numsides min_sides value rolldicenumsides print"you rolled "value simulate the rollowing of two nsided dice def rolldicensides )die randint nsides die randint nsides return die die call the main routine which we defined first main(
14,267
user-defined modules as you learned earlierpython includes standard library containing modules of functions and class definitions that can be used in our programs by using modulesthe language itself can remain relatively small while still providing extended functionality structured programs python programs can quickly become very large and unmanageableespecially if the entire user code is placed within single source file to help structure and manage large programspython allows the user to create their own modules modulewhich is text file that contains python source code and has py extensioncan be used to group class definitions and related functions typicallya large program consists of top-level source file and one or more supplemental modules the top-level file acts as the driver which contains the statements for the main flow of executionand the modules contain related componentswhich act as tools that are imported and used as needed the code segment below illustrates the use of modules in organizing structured program it consists of three python source filesa top-level driver (grades py)and two supplemental modules (iomod pyand compmod py(notethis is small simple program used for illustration purposes in practicea short program like this would more likely be placed in single module grades py the driver module which contains the statements creating the main flow of execution import iomod import compmod gradelist iomod extractgrades(avggrade compmod computeaveragegradelist iomod printreportgradelistavggrade
14,268
appendix user-defined modules iomod py module containing the routines used to extract and print grades def extractgrades()gradelist list(grade intinput("enter the first grade"while grade > gradelist appendgrade grade intinput("enter the next grade (or to quit)"return gradelist def printreportthelistavggrade )print"the average grade for the "len(thelist)"grades entered is"avggrade compmod py module which defines function for computing the average grade def computeaveragethelist )total for grade in thelist total +grade return total len(thelistto execute the programyou would enter the commandpython grades py at the command-line prompt since the driver program is the main file containing the starting point of execution the python interpreter will include each module specified within an import statement in this examplethat includes both iomod py and compmod py as indicated at the top of grades py the interpreter will only import module onceeven if it is encountered multiple times thusyou should always import module within source file if any component of that module is needed let the interpreter worry about omitting the module if it has already been included namespaces all identifiers in python live within namespacethe context in which identifiers are defined you can think of namespace as container or index in which various identifiers are stored when an identifier is referenced in python programa search is performed in particular namespace to determine if that identifier is valid the namespace concept allows programmers to create duplicate nameseach existing in different namespace in pythoneach module constitutes its own namespace any identifier defined within module may be freely used within that same module but what about identifiers defined within other modulesit depends how they are imported when the plain import statement is usedimport math math sqrtx
14,269
the contents of the module are made available for use in the current modulebut they are not made part of the current module' namespace that' why the identifiers have to be referenced using the dot/module name notation when the from/import version of the import statement is usedfrom math import powx the contents of the module are made available to the current module just like with the plain version but the identifiers from the imported module are included in the namespace of the current modulewhich can then be used as if they were defined within the current module the from/import version of the import statement has two forms when the asterisk is used as in the previous exampleeverything in the module is included and made available instead of including everythingyou can specify individual components to be includedfrom math import sqrtpow sqrtx powx you may be askingwhy are there two ways to import modules why not just use the from/import version and make all identifiers available within the current modulethe short answer isthere are times when different module authors may use the same name for function or classyet provide different functionality identifiers are unique within given namespacethere can be only one instance of each identifier in pythonunlike other languagesan identifier can be redefined at any time with the new definition replacing the original consider the code segment below which illustrates simple program consisting of top-level driver (main pyand two supplemental modules (moda py and modb pymain py import moda import modb intraw_input"enter value oney intraw_input"enter value twov moda userfnctxy modb userfnctxy moda py from math import def userfnctxy ) sqrtx return modb py def userfnctxy )return
14,270
appendix user-defined modules the driver needs to reference both instances of userfnct(from within its namespace by using the plain import statementboth versions of userfnct(will be imported and made available within the main py driver we can then include the module name as part of the referencev moda userfnctxy modb userfnctxy to direct the interpreter to specific version of the function had we imported the two versions of userfnct(into the current namespace using the from/import statementthen only the version defined within modb py would be available since the second definition of the function would have redefined the original from moda py
14,271
exceptions unforeseen errors can occur in program during run time due to faulty code or invalid input consider the following sample code segmentwhich attempts to access non-existent element of listmylist print mylist when this code is executedthe program aborts and the following message is displayedtraceback (most recent call last)file ""line in indexerrorlist index out of range the last line in the message provides information as to the type of run-time error that caused the program to abort in this casethere are only four elements in the list numbered and thus subscript is out of range pythonlike many other high-level programming languagesraises an exception when an error occurs an exception is an event that can be triggered and optionally handled during program execution when an exception is raised indicating an errorthe program can contain code to catch the exception and gracefully handle it when an exception is not handledthe program will abort as was the case in our example above catching exceptions consider the following example in which we want to extract an integer value from the user with the input(functionvalue intinput("enter an integer value"
14,272
appendix exceptions what happens if the user entered at the prompt instead of an actual numeric valuepython raises an exception which causes the program to abort with the following message printed to the terminal traceback (most recent call last)file ""line in valueerrorinvalid literal for int(with base ' xsince python cannot convert the string " xto an integer valueit raises an exception instead of having the program abort due to the exceptionwe can provide code to detect and catch the exception and request that the user try again while truetryvalue intinput("enter an integer value"break except valueerror print"you must enter an integer value try again the try block flags the code in which we want to catch any exceptions that may be raised during execution the except block indicates the action to take when the given type of exception is raised within the corresponding try block if no exception is raisedexecution flows normally and the except block is skipped when an exception is raisedthe normal flow of execution is interrupted if an except block is provided for the type of exception raisedexecution jumps to the first statement within that except block on the other handif there is no corresponding except blockthe program terminates raising exceptions python automatically raises exceptions when an error occurs during program execution for various language constructs and library modules but you can also raise an exception when you detect an error in your code consider the following functionwhich accepts two arguments and returns the minimum of the twodef minarg arg )if arg is none or arg is none raise typeerror"arguments to min(cannot be noneif arg arg return arg else return arg if we define this function as accepting two comparable values other than none and return the minimum of the twowe need to make sure the arguments are valid that isneither argument is null if one or both of the arguments is nullthen we raise typeerror exception to flag an error using the raise statement consider the function cally minxnone
14,273
which results in an error and the exception being raised the program aborts with the following messagetraceback (most recent call last)file "temp py"line in minxnone file "temp py"line in min raise typeerror"arguments to min(cannot be nonetypeerrorarguments to min(can not be none note the error message displayed in the last line of the output this message comes from the second argument to the raise statement when raising an exceptionan optional string can be given to provide descriptive error message to aide the programmer in debugging the code new in python xthe raise statement now requires the optional string message be included as an argument to the constructor of the exception class in prior versionsthe class name and the message could be separated by comma standard exceptions python provides number of built-in exceptions that can be raised by the language and its library modules in pythonexceptions are defined as classes from which an object is created the name of the class is given as an argument to the raise statement some of the more common exceptions are described nextc indexerror used when list or tuple index is out of range keyerror raised when dictionary key is not found in dictionary notimplementederror used in user-defined methods (especially in abstract classesto indicate the method is being used but has not yet been implemented runtimeerror raised to flag an error when no other exception type is appropriate typeerror raised when an incorrect data type is supplied to an operator or method valueerror raised when the correct data type is suppliedbut it is not an appropriate value assertions python also provides the assert statementwhich can be used to raise the special assertionerror exception the assert statement is used to state what we assume
14,274
appendix exceptions to be true at given point in the program if the assertion failspython raises an assertionerror and aborts the programunless the exception is caught the assert statement combines the testing of condition with raising an exception the difference between making an assertion and raising an exception is that the assert statements can be deactivated at run time consider the min(function defined earlier rewritten to use the assert statementdef minarg arg )assert arg is not none and arg is not none"arguments to min(cannot be noneif arg arg return arg else return arg there are two forms of the assert statementthough both test the given condition and raise the assertionerror exception when the condition fails the difference is the inclusion of the optional descriptionwhich provides information to the programmer as to the cause of the error assert value assert value " positive value is required exceptions should be raised in those instances where you expect errors may occur during execution that can be properly handled without aborting the program for examplewhen checking for valid user input or verifying successful network connection to serverthe program does not have to be aborted when the operation fails insteadyou can catch the exceptioninform the userand provide an alternate course of action this may not be the casehoweverwhen precondition fails due to logical error in the program for exampleif the programmer incorrectly attempts to access list element by supplying an out-of-range indexit may be impossible to recover from such an error in this casethe program should abort as the proper course of action thusassertions are best used for debugging program and testing preconditions while exceptions are best used to catch recoverable errors as we stated earlierassert statements can be deactivated at run time in the final product to prevent them from being executed since assertions are made to help debug and catch programming errorsonce you have fully tested the programwe would not expect these errors to occur by turning them offthe execution speed of the program can be improved in the final production environment in additionthe end user of the program will have little use for the debug information when implementing abstract data typesit' important that we ensure the proper execution of the various operations by verifying any stated preconditions the appropriate mechanism is to state assertions for the preconditions and allow the user of the adt to decide how they wish to handle the error in most casesthe appropriate step is to allow the program to abort thusin the textwe focus on stating assertions and omit further discussion of catching those exceptions
14,275
classes python supports both the procedural and object-oriented programming paradigms whereas the procedural paradigm is focused on the creation of functionsthe object-oriented paradigm is centered around the use of objects and classes an object is software entity that stores data class is the blueprint that describes the data stored in an object and defines the operations that can be performed on the object objects are created or instantiated from classesand each object is known as an instance of the class from which it was created the class definition pythonlike all object-oriented programming languagesallow programmers to define their own classes class definition is compound statement consisting of header and body the class header contains the keyword class followed by an identifier used to name the class the body of the class definition contains one or more method definitionsall of which must be indented to same indentation level suppose we want to define class to represent point or coordinate in the two-dimensional cartesian coordinate system the objects will need to store two valuesone for the -coordinate and one for the -coordinate we will also have to decide what operations we want to be able to perform on the objects created from the new class we can begin with framework for the new classclass point the methods are defined in the body one after the other notice that our class is named pointwhich starts with an uppercase letter while this is not requirement of the syntaxit is common programming practice in order to distinguish class name from variables and functions method is service or operation that can be performed on an object created from the given class method is very similar to function with several exceptions
14,276
appendix classes ( method is defined as part of class definition( method can only be used with an instance of the class in which it is definedand ( each method header must include parameter named selfwhich must be listed first new in python xall classes are automatically derived from the object base class even if it' not explicitly stated in the header definition constructors all classes should define special method known as the constructor which defines and initializes the data to be contained in the object the constructor is automatically called when an instance of the class is created in pythonthe constructor is named init and is usually listed first in the class definitionclass pointdef __init__selfxy )self xcoord self ycoord data attributes the data contained in an object is known as the object' data fields or data attributes the attributes are simply variableslike any other variable in pythonbut are stored in the object itself an object' attributes are accessed using the dot notation and appending the attribute name to the self reference any variables not prepended by the self reference are local to the method in which they are defined since variables in python are created when they are first assigned valuethe constructor is responsible for creating and initializing the data attributes the constructor of our point class needs to create two attributesone for each of the coordinate components this is done by the two assignment statementswhich create and initialize the attributes named xcoord and ycoord they are initialized respectively to the values of the two parametersx and (note that python also allows default arguments to be defined for methods just as it does for functions object instantiation an instance of user-defined class is created by invoking the constructor this is done by specifying the name of the class along with any required arguments as if it were function call for examplethe following statements create two objects from our point class and assigns them to the variables pointa and pointbpointa point( pointb point(
14,277
the results are illustrated in figure note that we never call the init method directly insteadpython allocates memory for the objectthen automatically calls the init method for the given class to initialize the new object the attributes of an object are also known as instance variables since new attributes are created for each instance of the class in our examplewe created two objects and each object has its own variables named xcoord and ycoord pointa xcoord ycoord pointb xcoord ycoord figure sample point objects the self reference you may have noticed that the constructor was defined with three parametersbut we supplied only two arguments when creating the objects when method is executedpython must know on which object the method was invoked in order to know which attributes to reference as indicated earlierself is special parameter that must be included in each method definition and it must be listed first when method is calledthis parameter is automatically filled with reference to the object on which the method was invoked if the method defines additional parametersexplicit arguments must be passed to the method as part of the method call operations so farwe can create new objectbut we can' do anything with it nextwe need to define additional operations that can be performed on our point objects let' start by adding two methods that can be used to extract the individual xand -components of the point contained in the object (note that we only show the two new methodsbut assume the constructor defined earlier is still part of the class as indicated by the comment line class point def getxself )return self xcoord def getyself )return self ycoord we can use the new methods to extract and print the coordinates of one of the objects we just created
14,278
appendix classes pointa getx( pointa gety(print"(str( "str( ")when the getx(method is calledpython creates local variable for the self parameter and assigns it copy of the reference stored in pointaas illustrated by figure the body of the method is then executed since the instance variable is prepended with the self reference and self is an alias for pointathe value in the xcoord attribute of pointa will be returned pointa xcoord pointa getx(ycoord self pointb xcoord ycoord the local scope for this method invocation figure use of the self reference any object that stores data is said to have state the object' state is the current set of values that it contains objects are divided into two distinct categoriesmutable and immutable an immutable object is one in which the state cannot be changed once it has been created if the data fields of the object can be changed after the object has been createdthe object is said to be mutable so farthe objects created from our point class are immutable because we have no way of changing the coordinates stored in the objects we can add method to adjust or shift point along both the xand -axeswhich now makes our objects mutable since we have way to modify the data attributesclass point def shiftselfxincyinc )self xcoord +xinc self ycoord +yinc if we apply this new method to our pointa object with the method call pointa shift( )local variables are created for all three parameters and assigned the corresponding valuesas illustrated in the top of figure after the method is executedthe data attributes of the pointa object are modifiedas illustrated in the bottom of figure finallywe add method to our class that can be used to compute the euclidean distance between two instances of the point classclass point def distanceselfotherpoint )xdiff self xcoord otherpoint xcoord ydiff self ycoord otherpoint ycoord return math sqrtxdiff * ydiff *
14,279
pointa xcoord ycoord pointa pointa shift( self xinc yinc xcoord pointb xcoord ycoord ycoord pointb xcoord ycoord figure the local scope (topwhen calling pointa shift( , and the result after the call (bottomthe distance is computed between the self point and the otherpointwhich is passed as an argument figure illustrates the local variables that are created when applying the method with the call pointa distancepointb pointa xcoord pointa distance(pointbotherpoint self ycoord xcoord ycoord pointb figure the local scope when calling pointa distance(pointbd using modules class definition is typically placed within its own module or combined with other common classes in single module this helps to organize and manage programs that consist of multiple classes when class is neededit can be imported from the module just like we would do with any of the standard modules for examplesuppose the point class is defined in the point py moduleas shown in listing to use the point class as illustrated by the earlier exampleswe must first import it from the point py modulefrom point import point create two point objects pointa point( , pointb point( , get and print the coordinates of pointa pointa getx( pointa gety(print"(str( "str( ")shift pointa and compute the distance between the two points pointa shift( pointa distancepointb
14,280
appendix classes listing the point py module implements the point class for representing points in the - cartesian coordinate system import math class point creates point object def __init__selfxy )self xcoord self ycoord returns the coordinate of the point def getxself )return self xcoord returns the coordinate of the point def getyself )return self ycoord shifts the point by xinc and yinc def shiftselfxincyinc )self _xcoord +xinc self _ycoord +yinc computes the distance between this point and the otherpoint def distanceselfotherpoint )xdiff self xcoord otherpoint xcoord ydiff self ycoord otherpoint ycoord return math sqrtxdiff * ydiff * while any form of the import statement can be usedin this text we will always use the from/import version and explicitly indicate the class to be imported from the given module hiding attributes object-oriented programming allows for the encapsulation of data and the operations that can be performed on that data in other wordsthe data attributes of an object and the methods that are defined for use with the object are combined in single definition and implementation the class definition in turn provides an interface to user-defined type the data attributes contained in an object are usually hidden from the client or user code that is outside the class only the methods defined by the class for use with the object should directly access the data attributes this prevents the accidental corruption of the data that can occur when directly accessed by code outside the class sometimes we may also need to protect methods from outside use such as with helper method helper methods are like any other methodbut they are commonly used in the implementation of class to allow for the
14,281
subdivision of larger method into smaller parts or to reduce code repetition by defining single method that can be called from within other methods as needed while most object-oriented languages provide mechanism to hide or protect the data attributes from outside accesspython does not insteadthe designer of class in python is supposed to indicate what data attributes and methods are suppose to be protected it' then the responsibility of the user of the class not to violate this protection in this textwe use identifier names that begin with single underscore to flag those attributes and methods that should be protected and trust the user of the class to not attempt direct access to those members the class definition in listing illustrates the use of the single underscore to indicate protected attributes it defines line segmentwhich is specified by point objects that represent the endpoints several operations are also defined for use with line segment listing the line py module implements linesegment class constructed from point objects from point import point class linesegment creates line segment object def __init__selffrompointtopoint )self _pointa frompoint self _pointb topoint gets the starting point of the line segment def endpointaself )return self _pointa gets the ending point of the line segment def endpointbself )return self _pointb gets the length of the line segment def lengthself )return self _pointa distanceself _pointb determines if the line is parallel to the -axis def isverticalself )return self _startpoint getx(=self _endpoint getx(gets the slope of the line def slopeself )if self isvertical(not defined for vertical line return none else run self _pointa getx(self _pointb getx(rise self _pointa gety(self _pointb gety(return rise run
14,282
appendix classes you will note that we directly accessed the attributes of the otherpoint object from within the distance(method implemented earlier but we used the getx(and gety(methods to access the same values within the line class the reason for this is that otherpoint is an instance of the same class as the method we were implementing in that caseit' acceptable to directly access its attributes without violating the protection in the case of the line classhoweverisvertical(and slope(are not part of the point class thuswe must access the values stored in the attributes of the two points by using the getx(and gety(access methods or we would violate the protection in this case overloading operators in pythonwe can define and implement many of the standard python operators such as +*and =as part of our user-defined classes this allows for more natural use of the objects instead of having to call specific methods by name for examplesuppose we want to include an operation for comparing two point objects to determine if they are the equal instead of including named method such as isequal()we can implement the special method eq class point def __eq__selfrhspoint )return self xcoord =rhspoint xcoord and self ycoord =rhspoint ycoord which python automatically calls when point object is used on the lefthand side of the equality operator (==)if pointa =pointb print"the points are equal if we need to determine if point is at the originwe can also use the equality operator by first creating an unnamed point object whose coordinates are both set to zeroif pointa =point( print"the point is at the origin we can overload any of the operators by including special method in our class definition table provides list of the operators and the corresponding special methods that must be defined some of the special methods are actually called when an instance of the class is passed to built-in function suppose we define the str method as part of our point classclass point def __str__self )return "(str( "str( ")
14,283
operation class method strobj __str__self lenobj __len__self item in obj __contains__selfitem obj[ndx__getitem__selfndx obj[ndxvalue __setitem__selfndxvalue obj =rhs __eq__selfrhs obj rhs __lt__selfrhs obj <rhs __le__selfrhs obj !rhs __ne__selfrhs obj rhs __gt__selfrhs obj >rhs __ge__selfrhs obj rhs __add__selfrhs obj rhs __sub__selfrhs obj rhs __mul__selfrhs obj rhs __truediv__selfrhs obj /rhs __floordiv__selfrhs obj rhs __mod__selfrhs obj *rhs __pow__selfrhs obj +rhs __iadd__selfrhs obj -rhs __isub__selfrhs obj *rhs __imul__selfrhs obj /rhs __itruediv__selfrhs obj //rhs __ifloordiv__selfrhs obj %rhs __imod__selfrhs obj **rhs __ipow__selfrhs table methods for overloading the common python operators now we can convert point object to string or use the object directly within the print(function just as we would with an int or float objectmsg "the initial point is str(pointaprint"point "pointb the str method is automatically called when you attempt to print an object or convert the object to string if the str method is not overloaded by userdefined classthe default action is to print the object type and its reference address finallysuppose we also want to allow the subtraction operator to be used in computing the distance between two points we can define the sub special
14,284
appendix classes method and have it call the distance(methodclass point def __sub__selfrhspoint )return self distancerhspoint we could choose to only overload the subtraction operator for use in computing the distance instead of providing both named method and an operator in that casewe would provide the code for computing the distance directly within the sub method definitionclass point def __sub__selfrhspoint )xdiff self xcoord rhspoint xcoord ydiff self ycoord rhspoint ycoord return math sqrtxdiff * ydiff * inheritance pythonlike all object-oriented languagessupports class inheritance instead of creating new class from scratchwe can derive new class from an existing one the new class automatically inherits all data attributes and methods of the existing class without having to explicitly redefine the code this leads to hierarchical structure in which the newly derived class becomes the child of the original or parent class figure illustrates hierarchical diagram of derived classes representing the relationship between different types of bibliography entries the parent-child relationship produced from the derivation of new class is known as an is- relationship in which the derived class is more specific version of the original in the hierarchical class diagram shown in figure book is- publication and is- more specific component of book object object publication publication book book article article webpage webpage figure hierarchical class diagram representing types of bibliography entries
14,285
note the inclusion of the object class at the top of the hierarchy this is python built-in class from which every class is derivedwhether explicitly stated or not thusall of the classes defined earlier in the appendix were derived from the object class even though it was not indicated in the class definition inheritance allows us to reuse existing code without having to duplicate similar code after inheriting the properties of the parent classthe new child class can be tailored to specific purpose by adding new functionality or modifying the existing functionality of the parent class to add new functionalitythe child class can define new data attributes and methods while the functionality of existing methods can be overridden to provide new functionality as needed by the child deriving child classes to illustrate inheritancewe are going to define and implement the classes shown in figure which can be used to build bibliography the idea behind this example is that publication references can be created for each source cited in document and stored in list structure the collection of sources can then be printed at the end of the document to create the bibliography each class in our example will be used to store information related to specific type of bibliography entry every entry will contain at least three pieces of informationa unique user-defined string code for identifying specific entryand the title and author of the corresponding publication additional information will be maintained for each entrybut it varies depending on the type of entry we start with the publication base class used to store the minimum amount of information for each bibliography entryclass publication def __init__selfcodetitleauthor )self _code code self _title title self _author author gets the unique identification code for this entry def getcodeself )return self _code returns string containing formatted bibliography entry def getbibentryself )return '[self getcode('"self _title 'by self _author note the inclusion of the syntax object following the class name this tells python that the publication class is derived from the object class we could have omitted this explicit derivation as we did in the classes defined earlier in the appendixbut we included it for illustration of the default parent class in the publication classwe only define the three data fields that are common to the different types of bibliography entries the only information that we will need to obtain from each entry is the unique code valuewhich can be accessed using getcode()and string containing correctly formatted bibliography entry
14,286
appendix classes the latter is obtained using the getbibentry(method note that we have this method returning string that contains the codetitleand authorwhich can be used as part of each entry but this operation will have to be overridden by each entry type in order to produce correctly formatted representation for the given type nextwe define the book classwhich will be used to represent book sources within our bibliography it is derived from the publication class since it is more specific type of publication book entry will contain two additional pieces of information in addition to that contained in the publication classthe name of the publisher and the year of publication class bookpublication )def __init__selfcodetitleauthorpublisheryear )super(__init__codetitleauthor self _publisher publisher self _year year def getbibentryself return super(getbibentry('self _publisher 'self _year constructor is also defined for this class that includes parameters for all of the data to be contained in book entry each class is responsible for initializing its own data attributes thusnote the first line in the body of the constructor that is used to call the constructor of the parent class that constructor requires three argumentscodetitleand author after the parent class creates and initializes its own attributeswe can then create and initialize two new attributes needed by the child class the child class also overrides the getbibentry(method from the parent class in order to build and return string containing the bibliography entry for book source our implementation calls the parent' version of the getbibentry(method in order to format the codetitleand author part of the bibliography entry for book creating class instances so what happens when we create an instance of the book classconsider the following code segmentpub publication"test ""just test""rob greenbook book"smith ""the year that was""john smith""bookends publishing" which creates an instance of the publication class and an instance of the book class the pub object only contains the three data fields defined by the publication classwhile the book object contains all five fieldsthe three from the parent class and the two defined in the book class figure illustrates the contents
14,287
of the two objects in additionthe book object also inherits all of the parent' methods but since we have provided new definitions for the constructor and the getbibentry(methodthe only method actually inherited from the parent is the getcode(method pub code test test title just just aa test test author rob rob green green book publication code smith smith title the the year year that that was was author john john smith smith publisher bookends bookends publishing publishing year book figure the data attributes of the publication and book objects invoking methods the methods available to objects of each class are shown in figure note that the getbibentry(method of the publication class is inherited and made available to the book class publication publication __init__ publication getcode(publication getbibentry(book book __init__ publication getcode(book getbibentry(figure the methods available for use with publication and book objects what happens if we use the getbibentry(method on the book object as an argument to the print(functionprintbook getbibentry(it will print the bibliography entry shown here[smith "the year that wasby john smithbookends publishing which it does by calling the getbibentry(method defined by the book class that method first calls the parent' getbibentry(method and then concatenates the result of that call with the publisher and year data needed to form book entry the methods of child class can access the data attributes of the parent class it' up to the designer of the class to ensure they do not modify the attributes incorrectly
14,288
appendix classes nextwe extend the book class by defining the classwhich is used to represent single within book it adds two additional attributes to the three already defined by the book class and the two defined by the publication class class book )def __init__selfcodetitleauthorpublisheryear pages )super(__init__codetitleauthorpublisheryear self _self _pages pages def getbibentryself return super(getbibentry('str(self pp pages self _publisher 'self _year againthe constructor of the child class must call the parent' constructor with the use of the super(function this timethe five fields needed by the book class are passed as arguments to the constructor the two new fields defined by the child class are then created and initialized with the values from the appropriate arguments partial implementation of the remaining bibliography entry classes are defined below in similar fashion to those defined earlier class articlepublication )def __init__selfcodetitleauthorjournalvolumenumberyear )super(__init__codetitleauthor self _journal journal self _volume volume self _number number self _year year def getbibentryself class webpagepublication )def __init__selfcodetitleauthorurlmodified )super(__init__codetitleauthor self _url url self _modified modified def getbibentryself )
14,289
polymorphism the third concept related to object-oriented programming is that of polymorphism it is very powerful feature in which the decision as to the specific method to be called is made at run time suppose we add the str method to our publication class and simply have it call and return the result of the getbibentry(method as shown herenew version with __str__ method added class publicationobject def __init__selfcodetitleauthor )self _code code self _title title self _author author gets the unique identification code for this entry def getcodeself )return self _code returns string containing formatted bibliography entry def getbibentryself )return '[self getcode('"self _title 'by self _author def __str__self )return self getbibentry(rememberwhen an object is used within the print(functionthe str operator method is automatically called for that object so what happens if we print the pub and book objects created earlierprintpub printbook this results in the following output[test '"just testby rob green [smith "the year that wasby john smithbookends publishing but how is that possible since we did not define str method for the book classit has to do with polymorphism since the str method is defined by the parent classit will be inherited by the child class thuswhen the str method is executed via the print functionprintbook python looks at the list of methods available to instances of the book class and finds the getbibentry(method defined for that class and executes it thusthe str method correctly calls the getbibentry(method of the child classeven though the str method was defined in the parent class
14,290
14,291
[ python documentation [ alfred ahojohn hopcroftand jeffrey ullman data structures and algorithms addison-wesleyreadingma [ john bentley programming pearlshow to sort communications of the acm ( ): - march [ john bentley programming pearlsthe back of the envelope communications of the acm ( ): - march [ john bentley programming pearlsthanksheaps communications of the acm ( ): - march [ john bentley programming pearls addison-wesleyreadingma [ john bentley programming pearlsthe envelope is back communications of the acm ( ): - march [ timothy budd classic data structures addison-wesleyreadingma [ thomas cormencharles leisersonand ronald rivest introduction to algorithms mit presscambridgema [ nell dale +plus data strucutres jones and bartlettsudburyma [ nell dale and susan lilly pascal plus data structuresalgorithms and advanced programmingsua houghton mifflin co bostonma [ charles hamblin translation to and from polish notation computer journal : - [ hoare quicksort the computer journal : - [ john hopcroftalfred ahoand jeffrey ullman the design and analysis of computer algorithms addison-wesleyreadingma [ bing-chao huang and michael langston practical in-place merging communications of the acm ( ): -
14,292
bibliography [ donald knuth fundamental algorithmsvolume of the art of computer programming addison-wesleyreadingma nd edition [ donald knuth sorting and searchingvolume of the art of computer programming addison-wesleyreadingma nd edition [ mckenzier harriesand bell selecting hashing algorithm software practice and experience : - [ bernard moret decision trees and algorithms computing surveys : - [ rance necaise transitioning from java to python in cs journal of computing sciences in colleges ( ): - [ rance necaise python for java programmers necaiseweb org [ edward reingold comment on the evaluation of postfix expressions computer journal : [ igor rivinilan vardiand paul zimmermann the -queens problem the american mathematical monthly ( ): - [ hanan samet applications of spatial data structures addison-wesleyreadingma [ hanan samet the design and analysis of spatial data structures addisonwesleyreadingma [ john williams algorithm heapsort communications of the acm ( ): - [ nicklaus wirth algorithms data structures programs prentice hallupper saddle rivernj
14,293
abs() abstract data type activities calendar array bag big integer color histogram color image color map counter counting bag date deque edit buffer expression tree fraction grab bag grayscale image hash map histogram life grid line segment map matrix maze morse code tree multi-array multi-chain -queens board polygon polynomial postfix calculator priority queue queue reversi game logic search tree set sparse life grid sparse matrix stack student file reader student file writer time todo list vector abstraction accessor activation record activities calendar add() addchar() addtosortedlist() adtsee abstract data type advanceby() agent class aggregate method airline ticket counter algorithm algorithm analysis average case best case worst case alias amortized cost ancestors append() - appendterm() array - - - hardware multi-dimensional one-dimensional three-dimensional two-dimensional array class array py array class arrayheap py
14,294
index arrayiterator class arrayqueue py asgregorian() assertion asymptoticsee complexity analysis average case avl tree - avlinsert() avlleftbalance() avlmap class avlrightbalance() avlrightrotate() avlrotateleft() avlrotateright() avltree py avltreenode class backtracking bag counting bag grab bag linked list sequence simple bag class - bagiterator class baglistnode class balance factor balanced binary tree bar() base case base class basic operations best case big integer big- biginteger class bin sort binary file binary search recursive sequential binary search tree - binary tree - binarysearch() binaryset py bintreenode class block indentation book class - bounded priority queue bpriorityq py breadth-first traversal breakline() brute-force bstsee binary search tree bstbuild() bstinsert() bstmapiterator class bstmaximum() bstminimum() bstremove() bstsearch() bubble sort bubblesearch() buildhist py buildmaze() buildtree() built-in scope calendar call tree cell cellposition class - cellular automata class checkdates py checkdates py child class child node circular array circular linked list class inheritance class variables classes agent array array avlmap bag - biginteger book - colorimage date dlistnode editbuffer editbuffernode expressiontree grayscaleimage lifegrid
14,295
line listnode map math matrix maxheap maze multiarray object passenger point - - polynomial polytermnode publication - queue reversigamelogic rgbcolor set - sparselifegrid sparsematrix - stack stopiteration str studentfilereader studentmlistnode studentrecord ticketagent ticketcounterclass ticketcountersimulation - time trianglearray clear() clearcell() close() closed addressing closed hashing clusters collection collision color histogram color image color map colorimage class column-major order comparable comparison sort comparison-based search complete binary tree complex adt complex data type complex iterators complexity analysis complexity cases compmod py composite data type compound key compound statements compute() computefactors() computeindex() computeop() computer program computer programming computer simulations configure() constant of proportionality constant time constant variable constructor container contains() control structures count-controlled counter counting bag cubic time data abstraction data attributes data structure data type date() date - date() date class date py dayofweek() dayofweekname() dayofyear() decision tree default argument defining functions degree() deletechar() depth depth-first traversal deque dequeue() derived class descendent
14,296
index diceroll py dict() dictionarysee map difference() direct access discrete event simulation distance() distribution sort divide and conquer dlistnode class dominant term double hashing doubly linked list draw() driver py driver program dummy node dynamic data edges edit buffer editbuffer class editbuffer py editbuffernode class eight-queens problem element access elements empirical analysis empty bag empty container empty stack encapsulation enqueue() escape sequences eval() evalstr() evaltree() evaluate() event-controlled evolve() ex () ex () ex () ex () exception exitfound() exp() exponential time expression tree expressiontree class exptree py exptreenode class extend() external reference fact() factorial fetchall() fetchrecord() fibonacci sequence fifo file() findneg() findnextelement() findorderedposition() findpath() findposition() findslot() findsmallest() findsortedposition() first-infirst-out foo() formatted output fraction full binary tree function game of life game tree gameoflife py general list get() getbibentry() getbranch() getcode() getcodeseq() getdata() getline() getx() gety() global scope global variable grab bag grabitem() grades py grayscale image grayscaleimage class gregorian calendar gregorian date
14,297
handlearrival() handlebeginservice() handleendservice() handlexyz() hash() hash chains hash code hash function hash map hash table - closed hashing double hashing linear probing open hashing quadratic probing hashing hashmap py haskey() head reference heap - order property shape property heapsort height height-balance property helper method hierarchical structure histogram home position htsearch() idnum() immutable object import modules - index() infix information hiding inorder traversal input() - insert() insertion sort insertionsort() insertnode() instance instance scope instance variable instantiated interface interior node intersect() interset() iomod py is- relationship isempty() isequal() isequinox() isfinished() isfree() isfull() isleaf() isleapyear() issolstice() issubsetof() isvalidgregorian() isvalidsource() isvertical() isweekday() iterator - julian calendar key keyarray() keyword arguments knapsack problem knight' tour last-in first-out leaf node left child len() length() lettergrade() level level order traversal lexicographical order life grid life grid life py lifegrid class lifo line class line py line segment linear probe linear search linear time
14,298
updating dictionary delete dictionary elements python data structures binary tree create root inserting into tree traversing tree tree traversal algorithms python data structures search tree search for value in -tree python data structures heaps create heap creating heap inserting into heap removing from heap replacing in heap python data structures graphs display graph vertices display graph edges adding vertex adding an edge python data structures algorithm design characteristics of an algorithm how to write an algorithm python data structures divide and conquer binary search implementation python data structures recursion binary search using recursion python data structures backtracking vi
14,299
python data structures sorting algorithms bubble sort merge sort insertion sort shell sort selection sort python data structures searching algorithms linear search interpolation search python data structures graph algorithms depth first traversal breadth first traversal python data structures algorithm analysis algorithm complexity space complexity time complexity python data structures algorithm types asymptotic notations common asymptotic notations python data structures algorithm classes greedy algorithms divide and conquer dynamic programming python data structures amortized analysis python data structures algorithm justification vii