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 in...
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...
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 i...
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 recurs...
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...
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 s...
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 h...
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...
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 ...
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 acce...
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 cla...
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...
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 inserti...
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...
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 r...
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 wi...
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 r...
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 pivot...
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 _bsts...
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 remem...
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 pi...
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 i...
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 ...
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 greate...
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 ...
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 co...
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 t...
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 ...
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...
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 no...
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 wa...
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 otherwisea...
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 se...
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 follo...
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 opera...
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 ma...
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 wi...
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' reser...
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 f...
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 ...
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 v...
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 ...
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 operator...
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 fo...
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 ...
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...
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 th...
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 singl...
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 forma...
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 % up...
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 nu...
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 nes...
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 bo...
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 ...
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 immuta...
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 co...
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 ...
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 ...
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 usin...
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 p...
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(...
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 t...
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 explicitl...
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 e...
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 retur...
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 ...
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 s...
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 ...
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 ...
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 ...
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 u...
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 rece...
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...
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...
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 ...
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 ...
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' n...
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 ...
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 re...
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 illustrate...
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...
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 p...
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...
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 ...
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 compu...
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 inheritanc...
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...
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 gr...
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__cod...
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 getbibent...
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 pr...
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 ex...
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 p...
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...
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 - tim...
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 editbuf...
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 ...
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...
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 algorit...