id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
13,900 | algorithm analysis modifying an element the setitem method for the sparsematrix class is bit more involved than that for the matrix class the value of an element cannot be directly set as was done when using the - array insteadthere are four possible conditions the element is in the list (and thus non-zeroand the new v... |
13,901 | verify the size of the two matrices to ensure they are the same as required by matrix addition create new sparsematrix object with the same number of rows and columns as the other two duplicate the elements of the self matrix and store them in the new matrix iterate over the element list of the righthand side matrix (r... |
13,902 | algorithm analysis efficiency analysis to evaluate the various operations of the sparse matrixwe can assume square matrix since this would be the worst possible case we begin with the findposition(helper methodwhich performs sequential search over the list of non-zero entries the worst case occurs when every item in th... |
13,903 | operation matrix sparse matrix constructor ( ( numrows( ( ( numcols( ( ( scaleby(xo( (kx [ ,jo( (ks[ ,jx ( (kr ( ( table comparison of the worst case time-complexities for the matrix class implemented using - array and the sparsematrix class using list exercises arrange the following expressions from slowest to fastest... |
13,904 | algorithm analysis evaluate each of the following code segments and determine the (*for the best and worst cases assume an input size of (cfor in rangen (asum if = for in rangen sum + elif = for in range sum + else for in rangen sum + for in rangen if = sum + (bsum while sum + the slice operation is used to create new ... |
13,905 | sparselifegrid()creates new infinite-sized game grid all cells in the grid are initially set to dead minrange()returns -tuple (minrowmincolthat contains the minimum row index and the minimum column index that is currently occupied by live cell maxrange()returns -tuple (maxrowmaxcolthat contains the maximum row index an... |
13,906 | algorithm analysis class rgbcolor def __init__selfred green blue )self red red self green green self blue blue given the description of the operations for the color image adtimplement the abstract data type using - array that stores instances of the rgbcolor class note when setting the initial color in the constructor ... |
13,907 | searching and sorting when people collect and work with datathey eventually want to search for specific items within the collection or sort the collection for presentation or easy access searching and sorting are two of the most common applications found in computer science in this we explore these important topics and... |
13,908 | searching and sorting the linear search the simplest solution to the sequence search problem is the sequential or linear search algorithm this technique iterates over the sequenceone item at timeuntil the specific item is found or all items have been examined in pythona target item can be found in sequence using the in... |
13,909 | listing implementation of the linear search on an unsorted sequence def linearsearchthevaluestarget lenthevalues for in rangen if the target is in the ith elementreturn true if thevalues[ =target return true return false if not foundreturn false to analyze the sequential search algorithm for the worst casewe must first... |
13,910 | searching and sorting listing implementation of the linear search on sorted sequence def sortedlinearsearchthevaluesitem lenthevalues for in rangen if the target is found in the ith elementreturn true if thevalues[ =item return true if target is larger than the ith elementit' not in the sequence elif thevalues[iitem re... |
13,911 | this taskmost people would not begin with the first exam and flip through one at time until the requested exam is foundas would be done with linear search insteadyou would probably flip to the middle and determine if the requested exam comes alphabetically before or after that one assuming jessica' paper follows alphab... |
13,912 | searching and sorting implementation the python implementation of the binary search algorithm is provided in listing the variables low and high are used to mark the range of elements in the sequence currently under consideration when the search beginsthis range is the entire sequence since the target item can be anywhe... |
13,913 | ( low ( high low ( high high mid low ( mid low ( mid high mid low high ( low high mid figure the steps performed by the binary search algorithm in searching for (ainitial range of items(blocating the midpoint(celiminating the upper half(dmidpoint of the lower half(eeliminating the lower fourthand (ffinding the target i... |
13,914 | searching and sorting saw earlier in the the efficiency of some applications can be improved when working with sorted lists another common use of sorting is for the presentation of data in some organized fashion for examplewe may want to sort class roster by student namesort list of cities by zip code or populationrank... |
13,915 | the next two passes over the cards are illustrated below in the second pass the card with the second largest face value is positioned in the next-to-last position in the third and final passthe first two cards will be positioned correctly after swapping the two cardsall of the cards are now in their proper orderfrom sm... |
13,916 | searching and sorting figure first complete pass of the bubble sort algorithmwhich places in its correct position black boxes represent values being comparedarrows indicate exchanges listing implementation of the bubble sort algorithm sorts sequence in ascending order using the bubble sort algorithm def bubblesortthese... |
13,917 | figure result of applying the bubble sort algorithm to the sample sequence the gray boxes show the values that are in order after each outer-loop traversal of iterations for the inner loop will be the sum of the first integerswhich equals ( resulting in run time of ( bubble sort is considered one of the most inefficien... |
13,918 | searching and sorting in this casethere would be no need to sort the sequence but our implementation still performs all iterations because it has no way of knowing the sequence is already sorted the bubble sort algorithm can be improved by having it terminate early and not require it to perform all iterations when the ... |
13,919 | we pick up the and add it to proper sorted positionwhich will be on the right side since there are no cards with smaller face value left on the table cards on the table our hand this process is continued until all of the cards have been picked up and placed in our hand in the correct sorted order from smallest to large... |
13,920 | searching and sorting the process starts by finding the smallest value in the sequence and swaps it with the value in the first position of the sequence the second smallest value is then found and swapped with the value in the second position this process continues positioning each successive value by selecting them fr... |
13,921 | figure result of applying the selection sort algorithm to our sample array the gray boxes show the values that have been sortedthe black boxes show the values that are swapped during each iteration of the algorithm |
13,922 | searching and sorting this process continuesone card at timeuntil all of the cards have been removed from the table and placed into our hand in their proper sorted position pick up the next card on top ( pick up the last card ( the resulting hand the insertion sort maintains collection of sorted items and collection of... |
13,923 | works its way to the front after finding the proper positionthe item is inserted figure illustrates the application of this algorithm on an array of integer values the insertion sort is an example of sorting algorithm in which the best and worst cases are different determining the different cases and the corresponding ... |
13,924 | searching and sorting working with sorted lists the efficiency of some algorithms can be improved when working with sequences containing sorted values we saw this earlier when performing search using the binary search algorithm on sorted sequence sorting algorithms can be used to create sorted sequencebut they are typi... |
13,925 | listing finding the location of target value using the binary search modified version of the binary search that returns the index within sorted sequence indicating where the target should be located def findsortedpositionthelisttarget )low high len(thelist while low <high mid (high low/ if thelist[mid=target return mid... |
13,926 | searching and sorting ( low ( high low ( mid high low ( high mid low ( mid high low high mid ( low high mid ( mid high low ( mid high/low ( high low mid figure performing binary search on sorted list when searching for value last exam flipped onto the new stack you now have single stack of exams in alphabetical order s... |
13,927 | listb lista newlist figure the iterative steps for merging two sorted lists into new sorted list and are index variables indicating the next value to be merged from the respective list of selecting the next largest value to be added to the new merged list during the iteration of the loopthe value at lista[ais compared ... |
13,928 | searching and sorting listing merging two sorted lists merges two sorted lists to create and return new sorted list def mergesortedlistslistalistb create the new list and initialize the list markers newlist list( merge the two lists together until one is empty while lenlista and lenlistb if lista[alistb[bnewlist append... |
13,929 | in all values from either lista or listb being copied to the newlist and all but one value from the other for total of iterations thenone of the next two loops will execute single iteration in order to copy the last value to the newlist the minimum number of iterations performed by the first loop occurs when all values... |
13,930 | searching and sorting listing the binaryset py module implementation of the set adt using sorted list class set creates an empty set instance def __init__self )self _theelements list(returns the number of items in the set def __len__self )return lenself _theelements determines if an element is in the set def __contains... |
13,931 | short-circuit evaluation most programming languages use shortcircuit evaluation when testing compound logical expressions if the result of the compound expression is known after evaluating the first componentthe evaluation ends and returns the result for examplein evaluating the logical expression and is falsethen ther... |
13,932 | searching and sorting we can implement the issubsetof(method in the same fashion as was done in the original version that used the unsorted list as shown in lines - of listing to evaluate the efficiency of the methodwe again assume both sets contain elements the issubsetof(method performs traversal over the self set du... |
13,933 | new set union the efficiency of the set union operation can also be improved from the original version set union using two sorted lists is very similar to the problem of merging two sorted lists that was introduced in the previous section in that problemthe entire contents of the two sorted lists were merged into third... |
13,934 | searching and sorting comparing the implementations the implementation of the set adt using an unsorted list was quick and easybut after evaluating the various operationsit became apparent many of them were time consuming new implementation using sorted list to store the elements of the set and the binary search algori... |
13,935 | determine the worst case time complexity for each method of the map adt implemented in section modify the binary search algorithm to find the position of the first occurrence of value that can occur multiple times in the ordered list verify your algorithm is still (log design and implement function to find all negative... |
13,936 | searching and sorting colormap is lookup table or color palette containing limited set of colors early color graphics cards could only display up to unique colors at one time colormaps were used to specify which colors should be used to display color images on such device software applications were responsible for mapp... |
13,937 | linked structures an array is the most basic sequence container used to store and access collection of data it provides easy and direct access to the individual elements and is supported at the hardware level but arrays are limited in their functionality the python listwhich is also sequence containeris an abstract seq... |
13,938 | linked structures deletions but it does eliminate the constant time direct element access available with the array and python list thusit' not suitable for every data storage problem there are several varieties of linked lists the singly linked list is linear structure in which traversals start at the front and progres... |
13,939 | since the next field can contain reference to any type of objectwe can assign to it reference to one of the other listnode objects for examplesuppose we assign to the next field of object aa next which results in object being linked to object bas shown herea and finallywe can link object to object cb next resulting in ... |
13,940 | linked structures list figure provides an example of linked list consisting of five nodes the last node in the listcommonly called the tail nodeis indicated by null link reference most nodes in the list have no name and are simply referenced via the link field of the preceding node the first node in the listhowevermust... |
13,941 | in the next sectionwe explore the construction and management of singly linked list independent of its use in the implementation of any specific adt in later sections we then present examples to show how linked lists can be used to implement abstract data types we also include number of exercises at the end of the that... |
13,942 | linked structures (aafter initializing the temporary external reference head curnode (badvancing the external reference after printing value head curnode (cadvancing the external reference after printing value head curnode (dadvancing the external reference after printing value head curnode (eadvancing the external ref... |
13,943 | listing traversing linked list def traversalhead )curnode head while curnode is not none print curnode data curnode curnode next the list has been accessed the completion of the traversal is determined when curnode becomes nullas illustrated in figure (fafter accessing the last node in the listcurnode is advanced to th... |
13,944 | linked structures prepending nodes when working with an unordered listnew values can be inserted at any point within the list since we only maintain the head reference as part of the list structurewe can simply prepend new items with little effort the implementation is provided in listing prepending node can be done in... |
13,945 | our external reference to the list and in turnwe lose the list itself the resultsafter linking the new node into the listare shown in figure (cwhen modifying or changing links in linked listwe must consider the case when the list is empty for our implementationthe code works perfectly since the head reference will be n... |
13,946 | linked structures head prednode curnode (ahead (bfigure using second temporary reference to remove node from linked list(apositioning the second temporary reference variable prednodeand (bthe resulting list after removing from the linked list we now step through the code required for deleting node from singly linked li... |
13,947 | listing removing node from linked list given the head referenceremove target from linked list prednode none curnode head while curnode is not none and curnode data !target prednode curnode curnode curnode next if curnode is not none if curnode is head head curnode next else prednode next curnode next if the target is e... |
13,948 | linked structures listing the llistbag py module implements the bag adt using singly linked list class bag constructs an empty bag def __init__self )self _head none self _size returns the number of items in the bag def __len__self )return self _size determines if an item is contained in the bag def __contains__selftarg... |
13,949 | size head bag figure sample instance of the bag class within the same module it is specified in lines - at the bottom of the modulebut it is not intended for use outside the bag class the remove(method implements the removal operation as presented in the previous sectionbut with couple of modifications the if statement... |
13,950 | linked structures of data do not have to be shifted as is required by the python list this is especially true when prepending items on the other handthe python list is better choice in those applications where individual elements must be accessed by index this can be simulated with linked listbut it requires traversal ... |
13,951 | _bagiterator curnode bag size head figure sample bag and bagiterator objects at the beginning of the for loop more ways to build linked list earlier in the we saw that new nodes can be easily added to linked list by prepending them to the linked structure this is sufficient when the linked list is used to implement bas... |
13,952 | linked structures head tail newnode (ahead tail (bfigure appending node to linked list using tail reference(athe links required to append the nodeand (bthe resulting list after appending into the list following the last node the next field of the node referenced by tail is set to point to the new node the tail referenc... |
13,953 | head prednode tail curnode figure deleting the last node in list using tail reference of the list if it waswe must adjust the tail reference to point to the same node as prednodewhich is now the last node in the list the code for removing an item from linked list using tail reference is shown in listing if the list con... |
13,954 | linked structures linear search the linear search for use with the linked list can be modified to take advantage of the sorted items the only change required is to add second condition that terminates the loop early if we encounter value larger than the target the search routine for sorted linked list is shown in listi... |
13,955 | three cases can occur when inserting node into sorted linked listas illustrated in figure the node is inserted in the frontat the endor somewhere in the middle after finding the correct positiona new node is created and its next field is changed to point to the same node referenced by curnode this link is required no m... |
13,956 | linked structures reference to point to the new node if the two nodes are not aliasesthen the node is inserted by setting the next field of the node referenced by prednode to point to the new node this step is handled by lines - of listing traversing and deleting the traversal operation implemented for the unsorted lin... |
13,957 | an array of linked lists implementation to implement the sparse matrix adt using an array of sorted linked listswe create new sparsematrix classas shown in listing in the constructortwo class fields are createdone to store the number of columns in the matrix and another to store the array of head references to the link... |
13,958 | linked structures own variable if the element is already zero-entry and the new value is zerono action is required setting the value of matrix element requires (ntime in the worst casewhere is the number of columns in the matrix this value is obtained by observing that the most time-consuming part is the positioning of... |
13,959 | self _listofrows[rownewnode else prednode next newnode scales the matrix by the given scalar def scalebyselfscalar )for row in rangeself numrows(curnode self _listofrows[rowwhile curnode is not none curnode value *scalar curnode curnode next creates and returns new matrix that is the transpose of this matrix def transp... |
13,960 | linked structures matrix scaling the scaleby(method is very similar to the version used in the list implementation of the original sparse matrix adt from we need only traverse over each of the individual linked lists stored in the listofrows arrayduring which we scale the value stored in each node rememberthis is suffi... |
13,961 | operation - array python list linked lists constructor ( ( ( numrows( ( ( ( numcols( ( ( ( [ ,jo( (ko(ns[ ,jx ( (ko(ns scaleby(xo( (ko(kr ( ( (kntable comparison of the matrix and sparse matrix adt implementations applicationpolynomials polynomialswhich are an important concept throughout mathematics and scienceare ari... |
13,962 | linked structures addition two polynomials of the same variable can be summed by adding the coefficients of corresponding terms of equal degree the result is third polynomial consider the following two polynomials which we can add to yield new polynomial( ( subtraction is performed in similar fashion but the coefficien... |
13,963 | the polynomial adt given the overview of polynomialswe now turn our attention to defining the polynomial adt define polynomial adt polynomial is mathematical expression of variable constructed of one or more terms each term is of the form ai xi where ai is scalar coefficient and xi is the unknown variable of degree pol... |
13,964 | linked structures earlier we were limited to the use of list or dictionary but with the introduction of the linked list in this we now have an additional option the linked list has the advantage of requiring fewer shifts and no underlying array management as is required with the python list this is especially important... |
13,965 | listing partial implementation of the polynomial py module implementation of the polynomial adt using sorted linked list class polynomial create new polynomial object def __init__(selfdegree nonecoefficient none)if degree is none self _polyhead none else self _polyhead _polytermnode(degreecoefficientself _polytail self... |
13,966 | linked structures listing continued helper method for appending terms to the polynomial def _appendtermselfdegreecoefficient if coefficient ! newterm _polytermnodedegreecoefficient if self _polyhead is none self _polyhead newterm else self _polytail next newterm self _polytail newterm class for creating polynomial term... |
13,967 | appending terms we included tail reference in our linked list implementation for use by several of the polynomial arithmetic operations in order to perform fast append operations while the polynomial adt does not define an append operationwe want to provide helper method that implements this operation it will be used b... |
13,968 | linked structures lists consider the linked lists in figure representing three polynomials with the nodes positioned such that corresponding terms are aligned the top two lists represent the two polynomials and while the bottom list is the polynomial resulting from adding the other two lista polyhead - - - - polytail l... |
13,969 | listing efficient implementation of the polynomial add operation class polynomial def __add__selfrhspoly )assert self degree(> and rhspoly degree(> "addition only allowed on non-empty polynomials newpoly polynomial(nodea self _termlist nodeb rhspoly _termlist add corresponding terms until one list is empty while nodea ... |
13,970 | linked structures method is quite simple but not very efficient the implementation of the polynomial multiplication is provided in lines - of listing we leave as an exercise the proof that the mul method requires quadratic time in the worst case as well as the development of more efficient implementation listing implem... |
13,971 | exercises implement the following functions related to the singly linked list(athe removeall(headfunctionwhich accepts head reference to singly linked listunlinks and remove every node individually from the list (bthe splitinhalf(headfunctionwhich accepts head reference to singly linked listsplits the list in half and ... |
13,972 | linked structures the following questions are related to the sparse matrix adt (aimplement the remaining methods of the sparsematrix class presented in the using the array of sorted linked listsgetitem transpose()sub and mul (bdetermine the time-complexity for each of the sparsematrix methods implemented in part ( (cpr... |
13,973 | consider the vector adt from programming project (aimplement new version of the adt using an unsorted linked list (bevaluate your new implementation to determine the worst case run time of each operation (ccompare the run times of your new version of the vector adt to that of the original in programming project (dwhat ... |
13,974 | linked structures bigintegerinitvalue " )creates new big integer that is initialized to the integer value specified by the given string tostring ()returns string representation of the big integer comparable other )compares this big integer to the other big integer to determine their logical ordering this comparison can... |
13,975 | stacks in the previous we used the python list and linked list structures to implement variety of container abstract data types in this we introduce the stackwhich is type of container with restricted access that stores linear collection stacks are very common in computer science and are used in many types of problems ... |
13,976 | stacks illustrates new values being added to the top of the stack and one value being removed from the top define stack adt stack is data structure that stores linear collection of items with access limited to last-in first-out order adding and removing items is restricted to one end known as the top of the stack an em... |
13,977 | when the outer while loop terminates after the negative value is extractedthe contents of the stack will be as illustrated in figure notice the last value entered is at the top and the first is at the base if we pop the values from the stackthey will be removed in the reverse order from which they were pushed onto the ... |
13,978 | stacks listing the pyliststack py module implementation of the stack adt using python list class stack creates an empty stack def __init__self )self _theitems list(returns true if the stack is empty or false otherwise def isemptyself )return lenself = returns the number of items in the stack def __len__ self )return le... |
13,979 | listing the lliststack py module implementation of the stack adt using singly linked list class stack creates an empty stack def __init__self )self _top none self _size returns true if the stack is empty or false otherwise def isemptyself )return self _top is none returns the number of items in the stack def __len__sel... |
13,980 | stacks size top stack figure sample object of the stack adt implemented as linked list the peek(method simply returns reference to the data item in the first node after verifying the stack is not empty if the method were used on the stack represented by the linked list in figure reference to would be returned the peek ... |
13,981 | balanced delimiters number of applications use delimiters to group strings of text or simple data into subparts by marking the beginning and end of the group some common examples include mathematical expressionsprogramming languagesand the html markup language used by web browsers there are typically strict rules as to... |
13,982 | stacks delimiter for properly paired delimitersthe two should match thusif the top of the stack contains left bracket [then the next closing delimiter should be right bracket if the two delimiters matchwe know they are properly paired and can continue processing the source code but if they do not matchthen we know the ... |
13,983 | and matched with the preceding right parenthesis thusunbalanced delimiters in which there are more closing delimiters than opening ones can be detected when trying to pop from the stack and we detect the stack is empty operation stack current point of scan push int sumlistpop match empty int sumlistint valuespop match ... |
13,984 | stacks listing function for validating +source file implementation of the algorithm for validating balanced brackets in +source file from lliststack import stack def isvalidsourcesrcfile ) stack(for line in srcfile for token in line if token in "{[( pushtoken elif token in "}])if isempty(return false else left pop(if (... |
13,985 | scanning processsuppose we are evaluating string containing nine non-blank characters and have scanned the first threea ( dat this pointwe have no way of knowing if the addition operation is to be performed on the two variables and or if we have to save this information for later after moving to the the next character ... |
13,986 | stacks short expressions can be easily converted to postfix formeven those using parentheses consider the expression *( + )which would be written in postfix as abc+longer expressionssuch as the example from earliera* + /dare bit more involved to help in this conversion we can use simple algorithm place parentheses arou... |
13,987 | evaluating postfix expression requires the use of stack to store the operands or variables at the beginning of the expression until they are needed assume we are given valid postfix expression stored in string consisting of operators and single-letter variables we can evaluate the expression by scanning the stringone c... |
13,988 | stacks the postfix evaluation algorithm assumes valid expression but what happens if the expression is invalidconsider the following invalid expression in which there are more operands than available operatorsa after applying the algorithm to this expressionthere are two values remaining on the stack as illustrated in ... |
13,989 | token alg step ab*+ ab*+ ab*+ (apop top two valuesy (bcompute or (cab*+ (aerror xxxxxx stack description push value of push value of push result ( of the multiplication pop top two valuesy xxxxxx only one value on stacktwo needed table the sequence of algorithm steps taken when evaluating the invalid postfix expression... |
13,990 | stacks if applied to the maze problemthe brute-force method would require we start at the beginning and follow path until we either find the exit or encounter blocked passage if we hit wall instead of the exitwe would start over from the beginning and try different path but this would be time consuming since we would l... |
13,991 | to further aide in the algorithm developmentwe place certain restrictions on movement within the maze firstwe can only move one cell at time and only to open positionsthose not blocked by wall or previously used along the current path the latter prevents us from reusing cell as part of the solution since we want to fin... |
13,992 | stacks finding the exit from the starting position ( )we can examine our surroundings or more specifically the four neighboring cells and determine if we can move from this position we want to use systematic or well-ordered approach in finding the path thuswe always examine the neighboring cells in the same orderupdown... |
13,993 | soon discover there are no legal moves since we are blocked by wall on three sides and cell comprising part of our path since we can go no further from this cellwe have no choice but to go back to our previous position in cell ( when hitting dead endwe don' simply turn around and go back over cell previously visited as... |
13,994 | stacks define maze adt maze is two-dimensional structure divided into rows and columns of equal-sized cells the individual cells can be filled representing wall or empty representing an open space one cell is marked as the starting position and another as the exit mazenumrowsnumcols )creates new maze with all of the ce... |
13,995 | listing the solvemaze py program program for building and solving maze from maze import maze the main routine def main()maze buildmaze"mazefile txtif maze findpath(print"path found maze draw(else print"path not found builds maze based on text format in the given file def buildmazefilename )infile openfilename"rread the... |
13,996 | stacks ******the first line contains the size of the maze given as the number of rows and columns the two subsequent lines indicate the row and column indices of the starting and exit positions the remaining lines of text represent the maze itselfwith walls represented using hash symbol and open cells represented as bl... |
13,997 | accessed by the individual methods by using the named constantsthe values used to represent the maze wall and tokens could easily be changed if we were so inclined listing the maze py module implements the maze adt using - array from array import array from lliststack import stack class maze define constants to represe... |
13,998 | stacks listing continued resets the maze by removing all "pathand "triedtokens def resetself )prints text-based representation of the maze def drawself )returns true if the given cell position is valid move def _validmoveselfrowcol )return row > and row self numrows(and col > and col self numcols(and self _mazecells[ro... |
13,999 | mazecells startcell exitcell maze array row row col col cellposition cellposition figure sample maze adt object indices are within the valid range the two methods that set the starting and exit positions simply create and store cellposition objects while the creation of wall fills the indicated cell using one of the na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.