id
int64
0
25.6k
text
stringlengths
0
4.59k
14,600
the next shortest edgethe edge from vertex to vertex is currently being considered the set containing and is the set { adding the edge with end points and cannot be done because vertices and are already in the same set sothis edge is skipped it cannot be part of the minimum weighted spanning tree the next shortest edge...
14,601
graphs proof of correctness proving kruskal' algorithm correctly finds minimum weighted spanning tree can be done with proof by contradiction the proof starts by recognizing that there must be | |- edges in the spanning tree then we assume that some other edge would be better to add to the spanning tree than the edges ...
14,602
if we make sure there is only one copy of each setwe can determine if two sets are the same or not in ( time as well we can just compare their references to see whether they are the same set or not the keyword is in python will accomplish this so if we want to know that and refer to the same set we can write is and thi...
14,603
graphs the third operation that must be performed is the merging of the sets containing and this is where the partition comes in handy having found the root of the two treeswe simply make the root of one of the trees point to the root of the other tree we end up with this partition after merging these two sets , , , , ...
14,604
fig minimum cost paths and total cost from source vertex minimum cost path between any two vertices in weighted graph this algorithm can beand sometimes isgeneralized to find the minimum cost path between source vertex and all other vertices in graph this algorithm is known as dijkstra' algorithm figure shows the resul...
14,605
graphs dijkstra' algorithm shares some commonality with depth first search the algorithm proceeds as depth first search proceedsbut starts with single source eventually visiting every node within the graph there are two sets that dijkstra' algorithm maintains the first is an unvisited set this is set of vertices that y...
14,606
(| |time since this happens | timesthe complexity of the first step is (| | over the course of running the algorithm the rest of the steps consider those edges adjacent to current since the number of edges of any vertex in simpleundirected graph will always be less than | |the rest of the algorithm runs in less than (|...
14,607
graphs the and vertex attributes are not required in any graph representationbut to draw graph it is nice to have location information for the vertices all this information is stored in the xml filebut what about the three algorithms presented in this what information is actually needed by each algorithm when searching...
14,608
graph representations an edge class class edgedef __init__(self, , ,weight= )self self self weight weight def __lt__(self,other)return self weight other weight running dijkstra' algorithm benefits from having both the edge and vertex objects the weight of each edge is needed by the algorithm so storing the weight in th...
14,609
graphs some typical graph representations are vertex list with adjacency informationan edge listor an adjacency matrix review questions answer these short answermultiple choiceand true/false questions to test your mastery of the in the definition of graphg (ve)what does the and the stand for what is the difference in t...
14,610
fig sample weighteddirected graph problem there are two buckets in this problema gallon bucket and gallon bucket your job is to put exactly gallons in the gallon bucket the rules of the game say that you can completely fill bucket of wateryou can pour one bucket into anotherand you can completely dump bucket out on the...
14,611
graphs by removing states from the list which have more gallons than allowed in that bucket the program should print out the list of actions to take to get from no water in either bucket to four gallons in the five gallon pail the solution may not be the absolute best solutionbut it should be valid solution that is pri...
14,612
membership structures in chap we covered data structures that support insertiondeletionmembership testingand iteration for some applications testing membership may be enough iteration and deletion may not be necessary the classic example is that of spell checker consider the job of spell checker simple one may detect e...
14,613
membership structures bloom filters bloom filters are named for their creatorburton howard bloomwho originally proposed this idea in since then many authors have covered the implementations of bloom filters including alan tharp [ wikipediawhile not always the authoritative sourcehas very good discussion of bloom filter...
14,614
fig after inserting cowcatand dog into the bloom filter looking up an item in bloom filter requires hashing the value again with the same hash functions generating the indices into the bit array if the value at all indices in the bit array are onethen the lookup function reports success and otherwise failure consider l...
14,615
membership structures another equally effective way of generating independent hashing functions is to append some known value to the end of each item before it is hashed for instancea might be appended to the item before hashing it to get the first hash function could be appended to the item before hashing to get the s...
14,616
using this formula it is possible to solve for given an and desired probabilitypof false positives the formula is as follows = ln (ln ) finallysolving for above results in the following formula ln these two formulas tell us how many bits are required in our filter to guarantee maximum specified rate of false positives ...
14,617
membership structures fig after inserting cowcatratrabbitand dog into trie tries are appropriate when key values are made up of more than one unit and when the individual units of key may overlap with other item keys in factthe more overlap the key units havethe more compact the trie data structure in the problem of sp...
14,618
when items are inserted into the trie sentinel unit is added in the case of the spell checkera '$character is appended to the end of every word the sentinel is needed because words like rat are prefixes to words like ratchet without the sentinel character it would be unclear whether word ended or was only prefix of som...
14,619
membership structures if the first unit of the key matches the unit of the current nodethen the rest of the key is inserted into the follows link of the node otherwisethe key is inserted into the next link of the node building the trie recursively is simple howeveran iterative version would work just as well the iterat...
14,620
transposition of characters like teh instead of the dropped characters like thei instead of their extra characters like thre instead of the incorrect characters like thare instead of there if in searching in trie word is not foundthese alternatives can also be searched for to find selection of alternative spellings wha...
14,621
membership structures bloom filter requires more or less storage than trie when spell checkingwhich data type can be used for spelling correction how can you generate more than one hashing function for use in bloom filter add the words " ""an""ant""bat"and "batterto trie draw the trie data structure showing its structu...
14,622
heaps the word heap is used in couple of different contexts in computer science heap sometimes refers to an area of memory used for dynamic ( run-timememory allocation another meaningand the topic of this is data structure that is conceptually complete binary tree heaps are used in implementing priority queuesthe heaps...
14,623
heaps fig heap shape conceptually heap is treebut heaps are generally not stored as trees complete tree is tree that is full on all levels except the lowest level which is filled in from left to right because heaps are complete treesthey may be stored in an array an example will help in understanding heaps and the comp...
14,624
of children and parents the children of any element of the array can be calculated from the index of the parent leftchildindex parentindex rightchildindex parentindex using these formulae on fig we can see that the children of the root node ( index are (at index and (at index likewisethe children of are located at inde...
14,625
heaps def __siftupfrom(selfchildindex)'''childindex is the index of node in the heap this method sifts that node up as far as necessary to ensure that the path to the root satisfies the heap condition ''the sequence of values passed to the buildfrom method will be copied into the heap theneach subsequent value in the l...
14,626
fig building heap part two fig building heap part three right place parentindex ( )// we compare with the and swap the two elements this is the last iteration of sifting up because has now reached the root ( index of the heap after swapping the two values we get the heap in fig the heapsort algorithm version heaps have...
14,627
heaps descending order we'll call these two parts of the algorithm phase and phase ii to implement phase we'll need one new method in our heap class the addtoheap method def addtoheap(self,newobject)'''if the heap is fulldouble its current capacity add the newobject to the heapmaintaining it as heap of the same type an...
14,628
table child and parent indices childindex parentindex (childindex )// (swap (swap (stopfig heap after moving to correct location sifting up the in the heap' list results in two swaps before it reaches its final location figure shows the is swapped with the at index then it is swapped again with the at index at this poi...
14,629
heaps table heap levels versus heap size level of nodes at level ( - ( - ( - ( - for heap with items in itthe value of can be computed by adding up all the nodes at each level in the heap' tree to simplify our argument we'll assume that the heap is full binary tree - for some this is the sum of geometric sequence the s...
14,630
but applying the inequality presented above we have the following the term comes from the last summation from to from the inequality above there are ones that are part of the summation these can be factored out as = log < log ( <(log log ( = = = we now have lower and upper bound for our sum the same summation appears i...
14,631
heaps the curve of the log the area under the curve can be found by taking the definite integral from to nwhich in the picture is but in general would be from this we get the following inequality  log dx < log = nowconsider shifting the entire green area to the right by one in the figure abovethat' the orange area the...
14,632
applying this to our integral we have the following ln and dv dx du dx and    ln dx ln dx  ln    dx ln - ln ( we have proved that the lower bound is proportional to log similarlywe could prove that the upper bound is also proportional to log therefore the work done by inserting elements into heap using the __sif...
14,633
heaps fig just before phase ii fig after swapping first and last values if sortedthe would go at the end of the list since there are elements in the heapwe'll swap the and the by doing this is at its final position within sorted list the is not in the correct location within the heap sowe call the __siftdownfromto meth...
14,634
fig after the first pass of phase ii fig after the second pass of phase ii during the third pass of phase ii the is put in its final location and swapped with the to make room for it although __siftdownfromto is calledno movement of values within the heap occurs because the is at the top and is the largest value in the...
14,635
heaps fig after the third pass of phase ii fig after the fourth and final pass of phase ii analysis of phase ii the work of phase ii is in the calls to the __siftdownfromto method which is called times each call must sift down an element in tree that shrinks by one element each time earlier in this we did the analysis ...
14,636
sift down this best case scenario brings up good point if we could limit how far down the value is siftedwe might be able to speed up phase that' the topic or our next section the heapsort algorithm version in version onethe heapsort algorithm attained ( log ncomplexity during phase and phase ii in version twowe will b...
14,637
heaps childindex parentindex childindex parentindex since the second of these indices is beyond the last index of the listthe __siftdownfromto method will not consider childindex after considering the and the we see that those two nodes do in fact form heap as shown in fig we will show this in the following figures by ...
14,638
finallywe move backward in the list one more element to index this time we only need to look at the values of the two children because they will already be the largest values in their respective heaps calling __siftdownfromto on the first element of the list will pick the maximum value from and and will swap the with t...
14,639
heaps analysis of heapsort version recall that phase ii is when the values are in heap and extracted one at time to form the sorted list version phase ii of the heapsort algorithm is identical to version and has the same complexityo( log nversion phase on the other hand has changed from top down approach to building th...
14,640
fig binary heap of height similarlythe other like terms simplify so we end up with the following formula for - - ( - - (nwhere nodes in the last step of the simplification above we have the sum of the first - powers of also known as the sum of geometric sequence this sum is equal to raised to the powerminus one this ca...
14,641
heaps fig comparison of several sorting algorithms within sorted list quicksort is more efficient than heapsort even though they have the same computational complexity examining fig we see selection sort operating with th ( complexitywhich is not acceptable except for very short lists the quicksort algorithm behaves mo...
14,642
without searching the entire heapunless it happens to be equal or greater to the largest value and you have largest on top heap likewiseif you have smallest on top heap and are looking for valueyou would have to look at all values unless the value you are searching for is equal or smaller than the smallest value common...
14,643
heaps programming problems implement version of the heapsort algorithm run your own tests using heapsort and quicksort to compare the execution time of the two sorting algorithms output your data in the plot format and plot your data using the plotdata py program provided on the text website implement version and versi...
14,644
in chap binary search trees were defined along with recursive insert algorithm the discussion of binary search trees pointed out they have problems in some cases binary search trees can become unbalancedactually quite often when tree is unbalanced the complexity of insertdeleteand lookup operations can get as bad as (n...
14,645
balanced binary search trees binary search trees binary search tree comes in handy when large number of insertdeleteand lookup operations are required by an application while at times it is necessary to traverse the items in ascending or descending order consider website like wikipedia that provides access to large set...
14,646
if val root getval()root setleft(binarysearchtree __insert(root getleft(),val)elseroot setright(binarysearchtree __insert(root getright(),val)return root if items are inserted into binary search tree in ascending order the effect is that execution always progresses from line to and the result on line puts the new value...
14,647
balanced binary search trees implementation alternatives looking back at chap and the implementation of binary search treesinserting value into tree can be written recursively inserting into an avl tree can also be implemented recursively it is also possible to implement inserting value into an avl tree iterativelyusin...
14,648
avl treesbut perhaps bit more difficult to maintain than maintaining the height of each node in the tree later in the modifications to these algorithms are discussed that maintain the height of each node whether storing height or balance in avl treesthe complexity of the tree operations is not affected avl tree iterati...
14,649
balanced binary search trees fig avl tree case --no pivot node fig avl tree case --no rotate case adjust balances the pivot node exists furtherthe subtree of the pivot node in which the new node was added has the smaller height in this casejust change the balance of the nodes along the search path from the new node up ...
14,650
fig avl tree case --single rotation is rotation at the pivot node in the opposite direction of the imbalance after the rotation the tree is still binary search tree in additionthe subtree rooted at the pivot will be balanced once againdecreasing its overall height by one figure illustrates this subcase the value is to ...
14,651
balanced binary search trees fig avl tree case step rotate toward againthe tree is still binary search tree and the height of the subtree in the position of the original pivot node is not changed by the double rotation figure illustrates this situation the pivot in this case is the root of the tree the node containing ...
14,652
rotations both cases and are trivial to implement as they simply adjust balances case is by far the hardest of the cases to implement rotating subtree is the operation that keeps the tree balanced as new nodes are inserted into it for case the tree is in state where new node is going to be added to the tree causing an ...
14,653
balanced binary search trees fig avl tree case left rotation new value under bad child in the opposite direction of the imbalance for instancethe subtree in fig is weighted to the left and the new node is inserted to the right of the bad child an analogous situation occurs when the subtree is weighted to the right and ...
14,654
fig avl tree case steps and this copy belongs to 'acha
14,655
balanced binary search trees avl tree recursive insert when implementing recursive function it is much easier to write as stand-alone function as opposed to method of class this is because stand-alone method may be called on nothing ( none in the case of pythonwhile method must always have non-null self reference writi...
14,656
balances before returning implements cases one and two as described earlier in the case three is detected when balance of - or results from rebalancing in that case the pivot is found and rebalancing according to case can occur should pivot be foundno balancing need occur above the pivot this is the use of the self piv...
14,657
balanced binary search trees deleting an item from an avl tree deleting value from an avl tree can be accomplished in the same way as described in programming problem from chap howeverit is necessary to adjust balances on the way back from deleting the final leaf node this can be done either by maintaining path stack i...
14,658
take (log ntime but the overall time to insert or lookup an item might improve little bit this is the motivation for splay tree in splay treeeach insert or lookup moves the inserted or looked up value to the root of the tree through process called splaying when deleting valuethe parent may be splayed to the root of the...
14,659
balanced binary search trees would-be parent of the value if the value is not found in the tree deletion from the tree can be implemented like delete from any other binary search tree as described in problem of chap when value is deleted from binary search tree the parent of the deleted node is splayed to the root of t...
14,660
fig splay tree double-left rotate fig splay tree right-left rotate this copy belongs to 'acha
14,661
balanced binary search trees fig splay tree left-right rotate do after the rotate operations depicted in figs and the subtree rooted at the child appears to be more balanced than before those rotations notice that doing left-right rotation is not the same as doing left rotation followed by right rotation the splay left...
14,662
fig splay tree example inserting new value into binary search tree without recursion is possible using while loop the while loop moves from the root of the tree to the leaf node which will become the new node' parent at which point the loop terminatesthe new node is createdand the parent is hooked up to its new child a...
14,663
balanced binary search trees one method of deleting node from splay tree is accomplished by deleting just as you would in binary search tree if the node to delete has zero or one child it is trivial to delete the node if the node to delete has two childrenthen the leftmost value in its right subtree can replace the val...
14,664
performance analysis in the worst case splay tree may become stick resulting in (ncomplexity for each lookupinsertand delete operation while avl trees guarantee (log ntime for lookupinsertand delete operations it would appear that avl trees might have better performance howeverthis does not seem to be the case in pract...
14,665
balanced binary search trees analysis of this is done on case by case basis and is not present in this text but may be found in texts on-line these proofs show that splay trees do indeed operate as efficiently as avl trees on randomly accessed data in additionthe splaying operation used when inserting or looking up val...
14,666
review questions answer these short answermultiple choiceand true/false questions to test your mastery of the what is the balance of node in an avl tree how does the balance of node relate to its height how does an avl tree make use of the balance of node what is pivot node what is bad child in relationship to avl tree...
14,667
balanced binary search trees implement two of the programming problems - in this and then write test program that generates random list of integers time inserting the values into the first implementation and then time inserting each value into the second implementation record all times in the xml format needed by the p...
14,668
-trees this covers one of the more important data structures of the last thirty years -trees are primarily used by relational databases to efficiently implement an operation called join -trees have other properties that are also useful for databases including ordering of rows within tablefast delete capabilityand seque...
14,669
-trees fig dairy database entity relationship diagram these nutrients are called feedattribtypes there is many-to-many relationship between feeds and feedattribtypes feed has many feed attributesor nutrients each nutrient or feed attribute type appears in more than one feed this relationship this copy belongs to 'acha
14,670
fig many to many relationship is depicted in fig the forks on the two ends of the line represent the manyto-many relationship between feeds and feed attribute types many-to-many relationships cannot be represented in relational database without going through process called reification reification introduces new entitie...
14,671
-trees with subset of the columns of this table the ellipses ( the indicate omitted rows within the database the full table is available as feed tbl on the text website the feed table 'corn silag 'almond hul 'molasswet 'liq cit pl 'whey 'sf corn 'dry min 'min plts 'mineral 'hay lact 'dry hay 'oat hay 'hlg 'cuphay 'hay ...
14,672
'mg 'fat 'magnesium as of dm'fat as of dm the table in sect contains subset of the records in the feedattribtype tableavailable as feedattribtype tbl on the text website the full table has different rows each containing fields as with the feed tablethe feedattribtype table is organized into rows and columns subset of t...
14,673
-trees corn silag corn silag mg corn silag fat almond hul almond hul ca almond hul rfv almond hul almond hul almond hul mg almond hul fat relational databases are often called sql databases sql stands for system query language sql is language for querying relational databases sql can be used to build temporary tables l...
14,674
fieldnum is zero based record is string containing the record coltypes is the types for each of the columns in the record offset for in range(fieldnum)coltype coltypes[ if coltype ="int"offset+= elif coltype[: ="char"size int(coltype[ :]offset +size elif coltype ="float"offset+= return val def main()select feed feednum...
14,675
-trees the readrecord function def readrecord(file,recnum,recsize)file seek(recnum*recsizerecord file read(recsizereturn record python includes seek method on files to position the read head of disk to byte offset within file the read method on files reads given number of bytes and returns them as string to test this r...
14,676
we can' assume that database table will alwaysor everbe sorted according to one field databases can have new records added and old records deleted at any time this is where the need for -tree comes from -tree is tree structure that is built over the topso to speakof database table to provide (log nlookup time to any re...
14,677
-trees attribtypetablereclength int(indexfile readline()attribtypeindex eval(indexfile readline()elseattribtypeindex btree( attribtable open("feedattribtype tbl"," "offset for record in attribtablefeedattribtypeid readfield(record,attribtypecols, anitem item(feedattribtypeid,offsetattribtypeindex insert(anitemoffset+= ...
14,678
fig sample -tree that contains items that are all less than the item to the right of the pointer pointer to the right of an item points to node where all the items are greater than the item in fig the items in node are all less than while the items in node are all greater than -trees are always balancedmeaning that all...
14,679
-trees the advantages of -trees -tree may contain entire records instead of just key/value pairs as appear in fig where the key/value pairs are the feedid and record number of each record in the feed table for instancethe entire record for feedid might be stored directly in the -tree where ( , currently appears in the ...
14,680
fig sample -tree with key deleted has been deleted from the -tree if sequential access is always handled through the -treeit would appear that the feed with feedid has been deleted from the table deleting an item from the table in this way is (log noperation while deleting by rewriting the entire file would take (ntime...
14,681
-trees -tree implementation looking up value in -tree is relatively simple and is left as an exercise for the reader inserting and deleting values are where all the action is alan tharp [ provides great discussion of both inserting and deleting values in -tree in this text we provide new examples and suggest both itera...
14,682
fig after splitting as result of inserting fig after inserting and fig inserting into the -tree causes splitting inserting an item causes one of two possible outcomes either the leaf node has room in it to add the new item or the leaf node splits resulting in middle value and new node being promoted to the parent this ...
14,683
-trees step above automatically handles any cascading splits that must occur after the recursive call the algorithm looks for any promoted value and handles it by either adding it into the node or by splitting again an iterative version of insert would proceed in similar manner as the recursive version except that the ...
14,684
fig after deleting the item containing fig after deleting the item containing fig after deleting the item containing the node containing to become unbalanced rebalancing is accomplished by borrowing items from its left sibling this is depicted in fig in fig notice that the rotates to the parent and the item containing ...
14,685
-trees fig after deleting the item containing fig after deleting the item containing that valuethe item containing in this casefrom the right subtree the result is depicted in fig deleting next causes the two sibling nodes to coalesce along with the separating item in the parent (the root in this casethe result is an e...
14,686
-tree delete or right sibling if that can' be donethen coalesce the child node with left or right sibling if the algorithm is implemented iteratively instead of recursively stack is needed to keep track of the path from the root node to the node containing the item to delete after deleting the item the stack is emptied...
14,687
-trees how does the use of an index improve the efficiency of the sample join operation presented in sect what advantages does -tree have over hash table implementation of an index what advantages does hash table have over -tree implementation of an index how can -tree index be created over table with millions of recor...
14,688
this text has focused on the interaction of algorithms with data structures many of the algorithms presented in this text deal with search and how to organize data so searching can be done efficiently many problems involve searching for an answer among many possible solutionsnot all of which are correct sometimesthere ...
14,689
heuristic search while heuristic search is not the solution to every problemas data sizes growthe use of heuristics will become more important this provides the necessary information to choose between at least some of these techniques to improve performance and solve some interesting large problems that would otherwise...
14,690
the algorithm in sect consists of while loop that finds path from start node to goal node when there is choice of direction on this pathall choices are pushed onto the stack by pushing all choicesif path leads to dead endthe algorithm just doesn' push anything new onto the stack the next time through the loopthe next p...
14,691
heuristic search possible diagonal moves would have the affect of moving through what looks like walls in the maze in some circumstances according to our direction preferencethe algorithm proceeds by making steps and in red then it proceeds to travel to the left into region when it gets to in region athere are no possi...
14,692
breadth first search breadth first search was first mentioned in chap the code for breadth first search differs in small way from depth first search instead of stacka queue is used to store the alternative choices the change to the code is smallbut the impact on the performance of the algorithm is quite big depth first...
14,693
heuristic search fig breadth first search of maze while it would be nice to be able to find optimal solutions to problemsbreadth first search is not really all that practical to use most interesting problems have high enough branching factors that breadth first search is impractical hill climbing depth first search was...
14,694
fig hill climbing search of maze the maze we can employ the manhattan distance as heuristic to guide us towards the goal we don' know the length of the path that will lead to the solution since we don' know all the details of the mazebut we can estimate the distance from where we are to the goal if we know the location...
14,695
heuristic search the location of the goal must be known prior to starting the search you must have heuristic that can be applied that will either under-estimate or provide an exact length of the path to the goal the better the heuristicthe better the hill climbing search algorithm hill climbing can perform well even in...
14,696
fig closed knight' tour and getting stuck in the middle of the board this heuristic is not perfect and some backtracking is still required to find the solution neverthelesswithout this heuristic there would be no hope in solving the problem in reasonable amount of time for board in factthe solution can' be found in rea...
14,697
heuristic search if we simply pick the next row in the sequence of rows so the search for the solution is only what column to place the next queen in to aide in forward checkingthe board can be represented as tuple(queen locationsavailable locationsthe first item in the tuple is the list of placed queens the second ite...
14,698
best first search sobreadth first search can find an optimal solution and deal with infinite search spacesbut it is not very efficient and can only be used in some smaller problems hill climbing is more efficientbut may not find an optimal solution combining the two we get best first search in best first search we orde...
14,699
heuristic search in the example shown here we did not do better than hill climbing of coursethat is only this example in general hill climbing may do worse than best first it all depends on the order that locations are searched in the search space howeverneither hill climbing or best first found the optimal solution li...