id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
14,100 | hash tables entrywhich results in the secondary clustering this occurs because the probe equation is based solely on the original hash slot better approach for reducing secondary clustering is to base the probe sequence on the key itself in double hashing when collision occursthe key is hashed by second function and th... |
14,101 | stored in the tablewe can easily create table large enough to hold the entire collection in many instanceshoweverthere is no way to know up front how many keys will be stored in the hash table in this casewe can start with table of some given size and then grow or expand the table as needed to make room for more entrie... |
14,102 | hash tables most of the probing techniques can benefit from table size that is prime number to determine the actual size of the new tablewe can first double the original size and then search for the first prime number greater than depending on the application and the type of probing usedyou may be able to simply double... |
14,103 | log( aa and for an unsuccessful search ( atable shows the average number of comparisons for both linear and quadratic probes when used with various load factors as the load factor increases beyond approximately / the average number of comparisons become very largeespecially for an unsuccessful search the data in the ta... |
14,104 | hash tables the key into the array elementsthe keys are inserted into the linked list referenced from the corresponding entrythere' no need to probe for different slot new keys can be prepended to the linked list since the nodes are in no particular order figure illustrates the use of separate chaining to build hash ta... |
14,105 | part of the hash operations mapping key to an entry in the hash table can be done in one stepbut the time to search the corresponding linked list is based on the length of that list in the worst casethe list will contain all of the keys stored in the hash tableresulting in linear time search as with closed hashingsepar... |
14,106 | hash tables integer keys are the easiest to hashbut there are many times when we have to deal with keys that are either strings or mixture of strings and integers when dealing with non-integer keysthe most common approach is to first convert the key to an integer value and then apply an integer-based hash function to t... |
14,107 | methods to generate an index within the valid range there are many different techniques available for this conversion the simplest approach is to sum the ascii values of the individual characters for exampleif we use this method to hash the string 'hashing'the result will be this approach works well with small hash tab... |
14,108 | hash tables should we useas we saw earliera load factor between / and / provides good performance in the average case for our implementation we are going to use load factor of / listing the hashmap py module implementation of the map adt using closed hashing and probe with double hashing from arrays import array class ... |
14,109 | returns an iterator for traversing the keys in the map def __iter__self )finds the slot containing the key or where the key can be added forinsert indicates if the search is for an insertionwhich locates the slot into which the new key can be added def _findslotselfkeyforinsert )compute the home slot and the step size ... |
14,110 | hash tables in the constructor (lines - )we create three attributestable stores the array used for the hash tablecount indicates the number of keys currently stored in the tableand maxcount indicates the maximum number of keys that can be stored in the table before exceeding the load factor instead of using floatingpoi... |
14,111 | to use objects of user-defined class as keys in the dictionarythe class must implement both the hash and eq methods the hash method should hash the contents of the object and return an integer that can be used by either of our two hash functionsh(and hp(the eq is needed for the equality comparison in line of listing wh... |
14,112 | hash tables which ensures an odd value more efficient solution would ensure the new size is always prime number by searching for the next prime number larger than the original array is saved in temporary variable and the new array is assigned to the table attribute the reason for assigning the new array to the attribut... |
14,113 | define histogram adt histogram is container that can be used to collect and store discrete frequency counts across multiple categories representing distribution of data the category objects must be comparable histogramcatseq )creates new histogram containing the categories provided in the given sequencecatseq the frequ... |
14,114 | hash tables listing continued print the histogram chart printchartgradehist determines the letter grade for the given numeric value def lettergradegrade )if grade > return 'aelif grade > return 'belif grade > return 'celif grade > return 'delse return 'fprints the histogram as horizontal bar chart def printchartgradehi... |
14,115 | grade distribution +***** +******** +********** +***** +**+----+----+----+----+----+----+----+--- implementation to implement the histogram adtwe must select an appropriate data structure for storing the categories and corresponding frequency counts there are several different structures and approaches that can be used... |
14,116 | hash tables listing continued increments the counter for the given category def inccountselfcategory )assert category in self _freqcounts"invalid histogram category value self _freqcounts valueofcategory self _freqcounts addcategoryvalue returns the sum of the frequency counts def totalcountself )total for cat in self ... |
14,117 | indicates full intensity thuswhite is represented with all three components set to while black is represented with all three components set to we can define an abstract data type for color histogram that closely follows that of the general histogramdefine color histogram adt color histogram is container that can be use... |
14,118 | hash tables same red and green components will be stored in the same chainwith only the blue components differing figure illustrates this - array of linked lists ** ** figure - array of linked lists used to store color counts in color histogram given digital image consisting of distinct pixelsall of which may contain u... |
14,119 | created and stored in the corresponding chain if we were to include second link within the same nodes used in the chains to store the colors and color countswe can then easily add each node to separate linked list this list can then be used to provide complete traversal over the entries in the histogram without wasting... |
14,120 | hash tables do the same as in exercise but use the following hash function to map the keys to the table entriesh(key( key show the contents of the hash table from exercise after rehashing with new table containing entries consider hash table of size that contains keys (awhat is the load factor(bwhat is the average numb... |
14,121 | advanced sorting we introduced the sorting problem in and explored three basic sorting algorithmsbut there are many others most sorting algorithms can be divided into two categoriescomparison sorts and distribution sorts in comparison sortthe data items can be arranged in either ascending (from smallest to largestor de... |
14,122 | advanced sorting algorithm description the algorithm starts by splitting the original list of values in the middle to create two sublistseach containing approximately the same number of values consider the list of integer values at the top of figure this list is first split following the element containing value these ... |
14,123 | figure the sublists are merged back together to create sorted list equal size the split is handled by first computing the midpoint of the list and then using the slice operation to create two new sublists the left sublist is then passed to recursive call of the pythonmergesort(function that portion of the list will be ... |
14,124 | advanced sorting new physical sublists are created in each recursive call as the list is subdivided we learned in that the slice operation can be time consuming since new list has to be created and the contents of the slice copied from the original list new list is also created each time two sublists are merged during ... |
14,125 | listing improved implementation of the merge sort algorithm sorts virtual subsequence in ascending order using merge sort def recmergesorttheseqfirstlasttmparray )the elements that comprise the virtual subsequence are indicated by the range [first lasttmparray is temporary storage used in the merging phase of the merge... |
14,126 | advanced sorting listing merging two ordered virtual sublists merges the two sorted virtual subsequences[left right[right endusing the tmparray for intermediate storage def mergevirtualseqtheseqleftrightendtmparray )initialize two subsequence index variables left right initialize an index variable for the resulting mer... |
14,127 | first mid end theseq the two virtual subsequences are merged into the temporary array tmparray the elements are copied from the temporary array back into the original sequence theseq figure temporary array is used to merge two virtual subsequences requires not only the sequence structure but also the index markers and ... |
14,128 | advanced sorting subsequences both implementations run in ( log ntime to see how we obtain this resultassume an array of elements is passed to recmergesort(on the first invocation of the recursive function for simplicitywe can let be power of which results in subsequences of equal size each time list is split as we saw... |
14,129 | timewe can determine the time required for each instance of the function based on the size of the subsequence processed by that instance to obtain the total running time of the merge sort algorithmwe need to compute the sum of the individual times in our sample call treewhere the first recursive call processes the enti... |
14,130 | advanced sorting algorithm description the quick sort is simple recursive algorithm that can be used to sort keys stored in either an array or list given the sequenceit performs the following steps the first key is selected as the pivotp the pivot value is used to partition the sequence into two segments or subsequence... |
14,131 | figure an abstract showing how quick sort merges the sorted segments and pivot value back into the original sequence implementation simple implementation using the slice operation can be devised for the quick sort algorithm as was done with the merge sort but it would require the use of temporary storage an efficient s... |
14,132 | advanced sorting listing implementation of the quick sort algorithm sorts an array or list using the recursive quick sort algorithm def quicksorttheseq ) lentheseq recquicksorttheseq - the recursive implementation using virtual segments def recquicksorttheseqfirstlast )check the base case if first >last return else sav... |
14,133 | are passed to the recursive calls in lines and of listing using the proper index ranges after the recursive callsthe recquicksort(function returns in the earlier descriptionthe sorted segments and pivot value had to be merged and stored back into the original sequence but since we are using virtual segmentsthe keys are... |
14,134 | advanced sorting after the two keys are swappedthe two markers are again shifted starting where they left off left right the left marker will be shifted to key value and the right marker to value left right left right once the two markers are shiftedthe corresponding keys are swapped left right and the process is repea... |
14,135 | pos the if statement at line of listing is included to prevent swap from occurring when the right marker is at the same position as the pivot value this situation will occur when there are no keys in the list that are smaller than the pivot finallythe function returns the pivot position for use in splitting the sequenc... |
14,136 | advanced sorting among the keys themselves to sort the sequence of keys while these distribution algorithms are fastthey are not general purpose sorting algorithms in other wordsthey cannot be applied to just any sequence of keys typicallythese algorithms are used when the keys have certain characteristics and for spec... |
14,137 | distribute the keys across the bins based on the ones column bin bin bin bin bin bin bin bin bin bin distribute the keys across the bins based on the tens column bin bin bin bin bin bin bin bin bin gather the keys back into the array bin gather the keys back into the array figure sorting an array of integer keys using ... |
14,138 | advanced sorting are once again gathered back into the arrayone bin at time as shown in step (dthe result is correct ordering of the keys from smallest to largestas shown at the bottom of figure in this examplethe largest value ( only contains two digits thuswe had to distribute and then gather the keys twiceonce for t... |
14,139 | listing implementation of the radix sort using an array of queues sorts sequence of positive integers using the radix sort algorithm from llistqueue import queue from array import array def radixsortintlistnumdigits )create an array of queues to represent the bins binarray array for in range )binarray[kqueue(the value ... |
14,140 | advanced sorting this implementation of the radix sort algorithm is straightforwardbut it requires the use of multiple queues to result in an efficient implementationwe must use the queue adt implemented as linked list or have direct access to the underlying list in order to use the python list version efficiency analy... |
14,141 | would create new sorted linked list by selecting and unlinking nodes from the original list and adding them to the new list origlist figure an unsorted singly linked list insertion sort simple approach for sorting linked list is to use the technique employed by the insertion sort algorithmtake each item from an unorder... |
14,142 | advanced sorting four stepsas illustrated in figure and implemented in lines - inserting the node into the new ordered list is handled by the addtosortedlist(functionwhich simply implements the operation from listing figure illustrates the results after each of the remaining iterations of the insertion sort algorithm w... |
14,143 | newlist origlist newlist origlist newlist origlist newlist origlist newlist origlist newlist origlist figure the results after each iteration of the linked list insertion sort algorithm |
14,144 | advanced sorting merge sort the merge sort algorithm is an excellent choice for sorting linked list unlike the sequence-based versionwhich requires additional storagewhen used with linked list the merge sort is efficient in both time and space the linked list versionwhich works in the same fashion as the sequence versi... |
14,145 | return the right sub list head reference return rightlist merges two sorted linked listreturns head reference for the new list def _mergelinkedlistssublistasublistb )create dummy node and insert it at the front of the list newlist listnodenone newtail newlist append nodes to the new list until one list is empty while s... |
14,146 | advanced sorting midpointor more specificallythe node located at the midpoint an easy way to find the midpoint would be to traverse through the list and count the number of nodes and then iterate the list until the node at the midpoint is located this is not the most efficient approach since it requires one and half tr... |
14,147 | after the midpoint is locatedthe link between the node referenced by midpoint and its successor can be removedcreating two sublistsas illustrated in figure before the link is removeda new head reference rightlist has to be created and initialized to reference the first node in the right sublist the rightlist head refer... |
14,148 | advanced sorting the first node to the sorted list with the use of dummy node at the front of the listas illustrated in figure the dummy node is only temporary and will not be part of the final sorted list thusafter the two sublists have been mergedthe function returns reference to the second node in the list (the firs... |
14,149 | exercises given the following sequence of keys ( )trace the indicated algorithm to produce recursive call tree when sorting the values in descending order (amerge sort (bquick sort do the same as in exercise but produce recursive call tree when sorting the values in ascending order show the distribution steps performed... |
14,150 | advanced sorting programming projects implement the addtosortedlist(function for use with the linked list version of the insertion sort algorithm create linked list version of the indicated algorithm (abubble sort (bselection sort create new version of the quick sort algorithm that chooses different key as the pivot in... |
14,151 | binary trees we have introduced and used several sequential structures throughout the text such as the arraypython listlinked liststacksand queues these structures organize data in linear fashion in which the data elements have "beforeand "afterrelationship they work well with many types of problemsbut some problems re... |
14,152 | binary trees bottom tree in figure trees are also used for making decisions one that you are most likely familiar with is the phoneor menutree when you call customer service for most businesses todayyou are greeted with an automated menu that you have to traverse the various menus are nodes in tree and the menu options... |
14,153 | is the root node nodes tcrand form path from to ( (bfigure sample tree with(athe root nodeand (ba path from to path the other nodes in the tree are accessed by following the edges starting with the root and progressing in the direction of the arrow until the destination node is reached the nodes encountered when follow... |
14,154 | binary trees nodefor examplenodes and are the children of all nodes that have the same parent are known as siblingsbut there is no direct access between siblings thuswe cannot directly access node from node or vice versa nodes nodes that have at least one child are known as interior nodes while nodes that have no child... |
14,155 | the binary tree trees can come in many different shapesand they can vary in the number of children allowed per node or in the way they organize data values within the nodes one of the most commonly used trees in computer science is the binary tree binary tree is tree in which each node can have at most two children one... |
14,156 | binary trees family tree terminologyeach level corresponds to generation the binary tree in figure ( )for examplecontains two nodes at level one ( and )four nodes at level two (defand )and two nodes at level three ( and ithe root node always occupies level zero the depth of node is its distance from the rootwith distan... |
14,157 | tree structure the height of the tree will be important in analyzing the time-complexities of various algorithms applied to binary trees the structural properties of binary trees can also play role in the efficiency of an algorithm in factsome algorithms require specific tree structures full binary tree is binary tree ... |
14,158 | binary trees perfect tree down to height - slots on the lowest level filled from left to right figure examples of complete binary trees depend on its applicationwe are going to create and work with the trees directly instead of creating generic binary tree class trees are generally illustrated as abstract structures wi... |
14,159 | root jj figure the physical implementation of binary tree simply follow the linksonce we reach leaf node we cannot directly access any other node in the tree preorder traversal tree traversal must begin with the root nodesince that is the only access into the tree after visiting the root nodewe can then traverse the no... |
14,160 | binary trees visit the node traverse the left subtree traverse the right subtree jj figure the logical ordering of the nodes with preorder traversal will be null reference when the binary tree is empty or we attempt to follow non-existent link for one or both of the children given binary tree of size na complete traver... |
14,161 | traverse the left subtree visit the node traverse the right subtree ii jj figure the logical ordering of the nodes with an inorder traversal postorder traversal we can also perform postorder traversal which can be viewed as the opposite of the preorder traversal in postorder traversalthe left and right subtrees of each... |
14,162 | binary trees breadth-first traversal the preorderinorderand postorder traversals are all examples of depth-first traversal that isthe nodes are traversed deeper in the tree before returning to higher-level nodes another type of traversal that can be performed on binary tree is the breadth-first traversal in breadth-fir... |
14,163 | listing breadth-first traversal on binary tree def breadthfirsttravbintree )create queue and add the root node to it queue enqueuebintree visit each node in the tree while not isempty(remove the next node from the queue and visit it node dequeue(printnode data add the two children to the queue if node left is not none ... |
14,164 | binary trees expression tree abstract data type arithmetic expressions can consist of both unary (-an!and binary operators ( bwe only consider expressions containing binary operators and leave the inclusion of unary operators as an exercise binary operators are stored in an expression tree with the left subtree contain... |
14,165 | listing the exptree py module class expressiontree builds an expression tree for the expression string def __init__selfexpstr )self _exptree none self _buildtreeexpstr evaluates the expression tree and returns the resulting value def evaluateselfvarmap )return self _evaltreeself _exptreevarmap returns string representa... |
14,166 | binary trees + / - figure expression tree for /( traversals to produce the correct expression trying to determine the minimum sets of parentheses that are required can be difficultbut we can easily create fully parenthesized expression(( ( ( ))we know an inorder traversal produces the correct ordering of operators and ... |
14,167 | listing the _buildstring helper method class expressiontree recursively builds string representation of the expression tree def _buildstringselftreenode )if the node is leafit' an operand if treenode left is none and treenode right is none return strtreenode element else otherwiseit' an operator expstr '(expstr +self _... |
14,168 | binary trees when leaf node is encounteredwe know it contains an operand but we must determine if that operand is single-integer digitin which case the integer value can be returnedor if it' single-letter variable in the case of the latterthe value for the variable must be located and returned from the user-supplied di... |
14,169 | when left parenthesis is encountereda new node is created and linked into the tree as the left child of the current node we then descend down to the new nodemaking the left child the new current node root token'(root current current the next token is the operand when an operand is encounteredthe data value of the curre... |
14,170 | binary trees constructing the expression tree involves performing one of five different steps for each token in the expression this same process can be used on larger expressions to construct each part of the tree consider figure which illustrates the steps required to build the tree for the expression (( * )+ the step... |
14,171 | read the operand set the value of the current node to the operand and move up to the parent of the current node read the right parenthesismove up to the parent of the current node since this is the last tokenwe are finished and the expression tree is complete having stepped through the construction of two sample expres... |
14,172 | binary trees the recbuildtree(method takes two argumentsa reference to the current node and queue containing the tokens that have yet to be processed the use of the queue is the easiest way to keep track of the tokens throughout the recursive process we indicated earlier that the expression will be supplied as stringbu... |
14,173 | (amin-heap (bmax-heap figure examples of heap definition the heap is specialized structure with limited operations we can insert new value into heap or extract and remove the root node' value from the heap in this sectionwe explore these operations for use with max-heap their application to min-heap is identical except... |
14,174 | binary trees be moved to another node where it can be legally placedand the value displaced by will have to be movedand so on until new leaf node is created for the last value displaced instead of starting from the top and searching for node in the tree where the new value can be properly placedwe can start at the bott... |
14,175 | is smaller and the two values have to be swappedas shown in part (dthe comparison is repeated againbut this time we find value is less than or equal to its parent and the process ends nowsuppose we add value to the heapas illustrated in figure the new node is created and filled with value and linked into the tree as th... |
14,176 | binary trees there is one less value in the heap since heap requires complete treethere is only one leaf that can be removedthe rightmost node on the lowest level to maintain complete tree and the heap order propertyan extraction requires several steps firstwe copy and save the value from the root nodewhich will be ret... |
14,177 | implementation throughout our discussionwe have used the abstract view of binary tree with nodes and edges to illustrate the heap structure while heap is binary treeit' seldomif everimplemented as dynamic linked structure due to the need of navigating the tree both top-down and bottom-up insteadwe can implement heap us... |
14,178 | binary trees determining if node' child link is null is simply matter of computing the index of the appropriate child and testing to see if the index is out of range for examplesuppose we want to test if node in the tree from figure has left child since the node is stored at index position we plug this value into the e... |
14,179 | save the root value and copy the last heap value to the root value self _elements[ self _count - self _elements[ self _elementsself _count sift the root value down the tree self _siftdown sift the value at the ndx element up the tree def _siftupselfndx )if ndx parent ndx / if self _elements[ndxself _elements[parenttmp ... |
14,180 | binary trees figure inserting value into the heap implemented as an array value in the current node and ( the sift-down operation has to be repeated on that child otherwisethe proper position of the value being sifted down has been located and the base case of the recursive operation is reached analysis inserting an it... |
14,181 | dequeued first the bounded priority queuein which the number of priorities is fixedallows for an efficient implementation with the use of an array of queues (section the unbounded priority queue does not place any restriction on the maximum positive integer value that can be used as the priority values with an unlimite... |
14,182 | binary trees heapsort the simplicity and efficiency of the heap structure can be applied to the sorting problem the heapsort algorithm builds heap from sequence of unsorted values and then extracts the items from the heap to create sorted sequence simple implementation consider the function in listing we create max-hea... |
14,183 | ( ( figure adding the first two values to the heap heap at the end of the array all we have to do is keep track of where the heap ends and the sequence of remaining values begin if we consider the first value in the arrayit constitutes max-heap of one itemas shown in figure (awhen adding value to heapit' copied to the ... |
14,184 | binary trees of the corresponding array the shaded part of the array indicates the items that are currently part of the array the boldfaced value indicates the next item to be sifted up the tree we have shown it is quite easy to build heap using the same array containing the values that are to be added to the heap simi... |
14,185 | just swapped with the root is shown in gray background notice that value is the largest value in the original array of unsorted values and when sorted belongs in this exact position at the end of the array finallythe value copied from the leaf to the root has to be sifted downas illustrated in figure (dif we repeat thi... |
14,186 | binary trees listing improved implementation of the heapsort algorithm sorts sequence in ascending order using the heapsort def heapsorttheseq ) len(theseqbuild max-heap within the same array for in rangen siftuptheseqi extract each value and rebuild the heap for in rangen- - tmp theseq[jtheseq[jtheseq[ theseq[ tmp sif... |
14,187 | decision trees another way to translate the message is with the use of decision tree decision tree models sequence of decisions or choices in which selections are made in stages from among multiple alternatives at each stage the stages in the decision are represented as nodes while the branches indicate the decisions t... |
14,188 | binary trees jj figure morse code modeled as binary decision tree given sequence in this casethe sequence represents the letter the path of the steps through the tree to decode the sequence is shown in figure jj figure decoding the morse code sequence what happens if we try to decode an invalid sequencefor exampletry d... |
14,189 | ll jj null figure decoding an invalid morse code sequence (define morse code tree adt morse code tree is decision tree that contains the letters of the alphabet and other special symbols in its nodes the nodes are organized based on the morse code sequence corresponding to each letter and symbol morsecodetree()builds t... |
14,190 | binary trees what is the maximum number of nodes possible in binary tree with levels given the following binary trees( ( ( ( ( (aindicate all of the structure properties that apply to each treefullperfectcomplete (bdetermine the size of each tree (cdetermine the height of each tree (ddetermine the width of each tree co... |
14,191 | (elist all of the nodes in the path to each of the following nodesi ii iii iv (fconsider node and list the node'si descendants ii ancestors iii siblings (gidentify the depth of each of the following nodesi ii iii iv determine the arithmetic expression represented by each of the following expression trees+/xx aa yy /bb ... |
14,192 | binary trees programming projects implement the function treesize(root)which computes the number of nodes in binary tree implement the function treeheight(root)which computes the height of binary tree implement the computeop(lvalueoperatorrvaluehelper method used to compute the value of binary operator when evaluating ... |
14,193 | search trees searchingwhich has been discussed throughout the textis very common operation and has been studied extensively linear search of an array or python list is very slowbut that can be improved with binary search even with the improved search timearrays and python lists have disadvantage when it comes to the in... |
14,194 | search trees we implemented hash table version of the map adt that improved the search times but its efficiency depends on the type of keys stored in the mapsince the choice of hash function can greatly impact the search operation throughout the we explore several different search treeseach of which we will use to impl... |
14,195 | listing partial implementation of the map adt using binary search tree class bstmap creates an empty map instance def __init__self )self _root none self _size returns the number of entries in the map def __len__self )return self _size returns an iterator for traversing the keys in the map def __iter__self )return _bstm... |
14,196 | search trees compare target to xx if target search the left subtree left subtree if target search the right subtree right subtree figure the structure of binary search tree is based on the search keys suppose we want to search for key value in the binary search tree from figure we begin by comparing the target to since... |
14,197 | listing searching for target key in binary search tree class bstmap determines if the map contains the given key def __contains__selfkey )return self _bstsearchself _rootkey is not none returns the value associated with the key def valueofselfkey )node self _bstsearchself _rootkey assert node is not none"invalid map ke... |
14,198 | search trees with the relationship between the keys if the root node contains keys in its left subtreethen it cannot possibly contain the minimum key value since all of the keys to the left of the root are smaller than the root what if the root node does not have left childin this casethe root would contain the smalles... |
14,199 | insertions when binary search tree is constructedthe keys are added one at time as the keys are inserteda new node is created for each key and linked into its proper position within the tree suppose we want to build binary search tree from the key list [ by inserting the keys in the order they are listed figure illustr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.