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 value is non-zero the element is in the listbut the new value is zeroturning the element into zero element the element is not currently in the list and the new value is non-zero the element is not currently in the listand the new value is zero the step in implementing the setitem methodas shown in lines - of listing is to determine if the element is in the list using the findposition(helper method if the entry is in the listwe either change the corresponding element to the new value if it is non-zero or we remove the entry from the list when the new value is zero on the other handif there is no entry for the given elementthen new matrixelement object must be created and appended to the list of coursethis is only done if the new value is non-zero matrix scaling scaling matrix requires multiplying each element of the matrix by given scale factor since the zero elements of the matrix are not affected by the scale factorthe implementation of this operation for the sparse matrix is as simple as traversing the list of matrixelement objects and scaling the corresponding value matrix addition in the add(method of the matrix class implemented in we iterated over the - array and added the valueselement by elementand stored the results in the corresponding element of the new matrix we could use the same loop structure shown here for the sparsematrix classadd the corresponding elements in the two matrices for in rangeself numrows(for in rangeself numcols(newmatrixrc selfrc rhsmatrixrc return newmatrix given matrix of size nthis implementation of the add operation requires ( time if the sparse matrix contains significant number of zero elementsthis can be inefficient insteadonly the non-zero elements contained in the two sparse matrices must be considered when adding to matrices the nested loops can be replaced with two separate loops to reduce the number of required iterations the new solution for sparse matrix addition requires four steps |
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 (rhsmatrixto add the non-zero values to the corresponding elements in the new matrix the implementation of the add operation is provided in listing the first two steps of the add operation are straightforward the third step of copying the elements of the self matrix to the new matrix requires list duplicationwhich is handled by the first loop the second loop handles the fourth step outlined above by iterating over the list of matrixelement objects in the rhsmatrix and adding their values to the corresponding values in the new sparse matrix note the use of the getitem and setitem methods in the second loop this is necessary since the two methods properly manage any zero elements that may currently exist in the newmatrix or that may result after adding corresponding elements listing implementation of the sparsematrix add operation class sparsematrix def __add__selfrhsmatrix )assert rhsmatrix numrows(=self numrows(and rhsmatrix numcols(=self numcols()"matrix sizes not compatible for the add operation create the new matrix newmatrix sparsematrixself numrows()self numcols(duplicate the lhs matrix the elements are mutablethus we must create new objects and not simply copy the references for element in self _elementlist dupelement _matrixelement(element rowelement colelement valuenewmatrix _elementlist appenddupelement iterate through each non-zero element of the rhsmatrix for element in rhsmatrix _elementlist get the value of the corresponding element in the new matrix value newmatrixelement rowelement col value +element value store the new value back to the new matrix newmatrixelement rowelement col value return the new matrix return newmatrix |
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 the list is examined but how many iterations does that requireit depends on the size of the element list from the definition of sparse matrixwe know it contains non-zero elements such that thusthe worst case run time of the helper method is (kthe setitem method calls findposition()which requires time it then changes the value of the target entrywhich is constant time operationor either removes an entry from the list or appends new entry the list operations require time in the worst caseresulting in an overall time of (kfor the set operation the getitem method can be evaluated in the same fashion and also has worst case time of (kto evaluate the operations that manipulate two sparsematrix objectswe can specify that both matrices are of the same size or that will represent the size of the larger of the two lists computing the worst case time for the new add(method requires that we first determine the complexity of the individual steps the size verification and new matrix creation are constant steps to duplicate the entries of the lefthand side sparse matrix requires time since append(has an amortized cost of ( the second loop iterates over the element list of the righthand side matrixwhich we have assumed also contains elements since the get and set element operations used within the loop each require time in the worst casethe loop requires or time combining this with the time for the previous stepsthe add operation is ( in the worst case is this time better than that for the add operation from the matrix class implemented as - arraythat depends on the size of if there were no zero elements in either matrixthen which results in worst case time of ( rememberhoweverthis implementation is meant to be used with sparse matrix in which in additionthe add operation only depends on the size of the element listk increasing the value of or does not increase the size of for the analysis of this algorithmm and simply provide maximum value for and are not variables in the equation the use of list as the underlying data structure to store the non-zero elements of sparse matrix is much better implementation than the use of - array as it can save significant storage space for large matrices on the other handit introduces element access operations that are more inefficient than when using the - array table provides comparison of the worst case time-complexities for several of the operations of the matrix class using - array and the sparsematrix class using list in later we will further explore the sparse matrix adt and attempt to improve the time-complexities of the various operations |
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 growth rate log log log log determine the (*for each of the following functionswhich represent the number of steps required for some algorithm (at (nn (et ( ( (bt ( (ft (nkkn log (ct ( log (gt (nk log (dt (nlog what is the time-complexity of the printcalendar(function implemented in exercise determine the (*for the following set operations implemented in difference()intersect()and remove( what is the time-complexity of the proper subset test operation implemented in exercise prove or show why the worst case time-complexity for the insert(and remove(list operations is ( |
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 list that contains subset of items from source list implement the slice(functiondef slicethelistfirstlast which accepts list and creates sublist of the values in thelist what is the worst case time for your implementation and what is the best case time implement the remaining methods of the sparsematrix classtranspose()getitem subtract()and multiply( determine the worst case time-complexities for the sparsematrix methods implemented in the previous question determine the worst case time-complexities for the methods of your reversigamelogic class implemented in programming project add python operator methods to the sparsematrix class that can be used in place of the named methods for several of the operations operator method add (rhsmatrixmul (rhsmatrixsub (rhsmatrixcurrent method add(rhsmatrixsubtract(rhsmatrixmultiply(rhsmatrixprogramming projects the game of life is defined for an infinite-sized grid in we defined the life grid adt to use fixed-size grid in which the user specified the width and height of the grid this was sufficient as an illustration of the use of - array for the implementation of the game of life but full implementation should allow for an infinite-sized grid implement the sparse life grid adt using an approach similar to the one used to implement the sparse matrix |
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 and the maximum column index that is currently occupied by live cell configurecoordlist )configures the grid for evolving the first generation the coordlist argument is sequence of -tuples with each tuple representing the coordinates (rcof the cells to be set as alive all remaining cells are cleared or set to dead clearcellrowcol )clears the individual cell (rowcoland sets it to dead the cell indices must be within the valid range of the grid setcellrowcol )sets the indicated cell (rowcolto be alive the cell indices must be within the valid range of the grid islivecellrow,col )returns boolean value indicating if the given cell (rowcolcontains live organism the cell indices must be within the valid range of the grid numliveneighborsrowcol )returns the number of live neighbors for the given cell (rowcolthe neighbors of cell include all of the cells immediately surrounding it in all directions for the cells along the border of the gridthe neighbors that fall outside the grid are assumed to be dead the cell indices must be within the valid range of the grid implement new version of the gameoflife py program to use your sparselifegrid class from the previous question repeat exercise from but use your new version of the gameoflife py program from the previous question the digital grayscale image was introduced in programming project and an abstract data type was defined and implemented for storing grayscale images color digital image is also two-dimensional raster imagebut unlike the grayscale imagethe pixels of color image store data representing colors instead of single grayscale value there are different ways to specify colorbut one of the most common is with the use of the discrete rgb color space individual colors are specified by three intensity values or components within the range [ ]one for each of the three primary colors that represent the amount of redgreenand blue light that must be added to produce the given color we can define the rgbcolor class for use in storing single color in the discrete rgb color space |
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 or when clearing the image to specific coloryou can store aliases to one rgbcolor object in each element of the array colorimagenrowsncols )creates new instance that consists of nrows and ncols of pixels each set to black width()returns the width of the image height()returns the height of the image clearcolor )clears the entire image by setting each pixel to the given rgb color getitem rowcol )returns the rgb color of the given pixel as an rgbcolor object the pixel coordinates must be within the valid range setitem rowcolcolor )set the given pixel to the given rgb color the pixel coordinates must be within the valid range color images can also be stored using three separate color channels in which the values of each color component is stored in separate data structure implement new version of the color image adt using three - arrays to store the redgreenand blue components of each pixel apply the row-major formula from section to map specific pixel given by (rowcolto an entry in the - arrays color image can be easily converted to grayscale image by converting each pixel of the color imagespecified by the three components (rgb)to grayscale value using the formula gray round the proportions applied to each color component in the formula corresponds to the levels of sensitivity with which humans see each of the three primary colorsredgreen and blue note the result from the equation must be converted capped to an integer in the range [ use the equation and implement the function def colortograyscalecolorimg )which accepts colorimage object as an argument and creates and returns new grayscaleimage that is the grayscale version of the given color image |
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 study some of the basic algorithms for use with sequence structures the searching problem will be discussed many times throughout the text as it can be applied to collections stored using many different data structuresnot just sequences we will also further explore the sorting problem in and with discussion of more advanced sorting algorithms searching searching is the process of selecting particular information from collection of data based on specific criteria you are familiar with this concept from your experience in performing web searches to locate pages containing certain words or phrases or when looking up phone number in the telephone book in this textwe restrict the term searching to refer to the process of finding specific item in collection of data items the search operation can be performed on many different data structures the sequence searchwhich is the focus in this involves finding an item within sequence using search key to identify the specific item key is unique value used to identify the data elements of collection in collections containing simple types such as integers or realsthe values themselves are the keys for collections of complex typesa specific data component has to be identified as the key in some instancesa key may consist of multiple componentswhich is also known as compound key |
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 operatorif key in thearray print"the key is in the array else print"the key is not in the array the use of the in operator makes our code simple and easy to read but it hides the inner workings underneaththe in operator is implemented as linear search consider the unsorted - array of integer values shown in figure (ato determine if value is in the arraythe search begins with the value in the first element since the first element does not contain the target valuethe next element in sequential order is compared to value this process is repeated until the item is found in the sixth position what if the item is not in the arrayfor examplesuppose we want to search for value in the sample array the search begins at the first entry as beforebut this time every item in the array is compared to the target value it cannot be determined that the value is not in the sequence until the entire array has been traversedas illustrated in figure ( (asearching for start (bsearching for start figure performing linear search on an unsorted array(athe target item is found and (bthe item is not in the array finding specific item the function in listing implements the sequential search algorithmwhich results in boolean value indicating success or failure of the search this is the same operation performed by the python in operator count-controlled loop is used to traverse through the sequence during which each element is compared against the target value if the item is in the sequencethe loop is terminated and true is returned otherwisea full traversal is performed and false is returned after the loop terminates |
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 determine what conditions constitute the worst case rememberthe worst case occurs when the algorithm performs the maximum number of steps for sequential searchthat occurs when the target item is not in the sequence and the loop iterates over the entire sequence assuming the sequence contains itemsthe linear search has worst case time of (nsearching sorted sequence linear search can also be performed on sorted sequencewhich is sequence containing values in specific order for examplethe values in the array illustrated in figure are in ascending or increasing numerical order that iseach value in the array is larger than its predecessor searching for start figure the linear search on sorted array linear search on sorted sequence works in the same fashion as that for the unsorted sequencewith one exception it' possible to terminate the search early when the value is not in the sequence instead of always having to perform complete traversal for examplesuppose we want to search for in the array from figure when the fourth itemwhich is value is examinedwe know value cannot be in the sorted sequence or it would come before the implementation of linear search on sorted sequence is shown in listing on the next page the only modification to the earlier version is the inclusion of test to determine if the current item within the sequence is larger than the target value if larger value is encounteredthe loop terminates and false is returned with the modification to the linear search algorithmwe have produced better versionbut the time-complexity remains the same the reason is that the worst case occurs when the value is not in the sequence and is larger than the last element in this casewe must still traverse the entire sequence of items |
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 return false return false the item is not in the sequence finding the smallest value instead of searching for specific value in an unsorted sequencesuppose we wanted to search for the smallest valuewhich is equivalent to applying python' min(function to the sequence linear search is performed as beforebut this time we must keep track of the smallest value found for each iteration through the loopas illustrated in listing to prime the loopwe assume the first value in the sequence is the smallest and start the comparisons at the second item since the smallest value can occur anywhere in the sequencewe must always perform complete traversalresulting in worst case time of (nlisting searching for the smallest value in an unsorted sequence def findsmallestthevalues ) lenthevalues assume the first item is the smallest value smallest thevalues[ determine if any other item in the sequence is smaller for in range if thelist[ismallest smallest thevalues[ireturn smallest return the smallest found the binary search the linear search algorithm for sorted sequence produced slight improvement over the linear search with an unsorted sequencebut both have linear timecomplexity in the worst case to improve the search time for sorted sequencewe can modify the search technique itself consider an example where you are given stack of examswhich are in alphabetical orderand are asked to find the exam for "jessica roberts in performing |
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 alphabetically after the middle oneyou know it cannot possibly be in the top half of the stack insteadyou would probably continue searching in similar fashion by splitting the remaining stack of exams in half to determine which portion contains jessica' exam this is an example of divide and conquer strategywhich entails dividing larger problem into smaller parts and conquering the smaller part algorithm description the binary search algorithm works in similar fashion to the process described above and can be applied to sorted sequence the algorithm starts by examining the middle item of the sorted sequenceresulting in one of three possible conditionsthe middle item is the target valuethe target value is less than the middle itemor the target is larger than the middle item since the sequence is orderedwe can eliminate half the values in the list when the target value is not found at the middle position consider the task of searching for value in the sorted array from figure we first determine which element contains the middle entry as illustrated in figure the middle entry contains which is greater than our target of thuswe can discard the upper half of the array from consideration since cannot possibly be in that part having eliminated the upper halfwe repeat the process on the lower half of the array we then find the middle item of the lower half and compare its value to the target since that entrywhich contains is less than the targetwe can eliminate the lower fourth of the array the process is repeated on the remaining items upon finding value in the middle entry from among those remainingthe process terminates successfully if we had not found the targetthe process would continue until either the target value was found or we had eliminated all values from consideration start figure searching for in sorted array using the binary search |
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 anywhere within the sequence the first step in each iteration is to determine the midpoint of the sequence if the sequence contains an even number of elementsthe mid point will be chosen such that the left sequence contains one less item than the right figure illustrates the positioning of the lowhighand mid markers as the algorithm progresses listing implementation of the binary search algorithm def binarysearchthevaluestarget start with the entire sequence of elements low high len(thevalues repeatedly subdivide the sequence in half until the target is found while low <high find the midpoint of the sequence mid (high low/ does the midpoint contain the targetif thevalues[mid=target return true or does the target precede the midpointelif target thevalues[midhigh mid or does it follow the midpointelse low mid if the sequence cannot be subdivided furtherwe're done return false after computing the midpointthe corresponding element in that position is examined if the midpoint contains the targetwe immediately return true otherwisewe determine if the target is less than the item at the midpoint or greater if it is lesswe adjust the high marker to be one less than the midpoint and if it is greaterwe adjust the low marker to be one greater than the midpoint in the next iteration of the loopthe only portion of the sequence considered are those elements between the low and high markersas adjusted this process is repeated until the item is found or the low marker becomes greater than the high marker this condition occurs when there are no items left to be processedindicating the target is not in the sorted sequence run time analysis to evaluate the efficiency of the the binary search algorithmassume the sorted sequence contains items we need to determine the maximum number of times the |
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 item while loop is executed the worst case occurs when the target value is not in the sequencethe same as for the linear search the difference with the binary search is that not every item in the sequence has to be examined before determining the target is not in the sequenceeven in the worst case since the sequence is sortedeach iteration of the loop can eliminate from consideration half of the remaining values as we saw earlier in section when the input size is repeatedly reduced by half during each iteration of loopthere will be log iterations in the worst case thusthe binary search algorithm has worst case time-complexity of (log )which is more efficient than the linear search sorting sorting is the process of arranging or ordering collection of items such that each item and its successor satisfy prescribed relationship the items can be simple valuessuch as integers and realsor more complex typessuch as student records or dictionary entries in either casethe ordering of the items is based on the value of sort key the key is the value itself when sorting simple types or it can be specific component or combination of components when sorting complex types we encounter many examples of sorting in everyday life consider the listings of phone bookthe definitions in dictionaryor the terms in an indexall of which are organized in alphabetical order to make finding an entry much easier as we |
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 order sat scoresor list entries on bank statement by date sorting is one of the most studied problems in computer science and extensive research has been done in this arearesulting in many different algorithms while python provides sort(method for sorting listit cannot be used with an array or other data structures in additionexploring the techniques used by some of the sorting algorithms for improving the efficiency of the sort problem may provide ideas that can be used with other types of problems in this sectionwe present three basic sorting algorithmsall of which can be applied to data stored in mutable sequence such as an array or list bubble sort simple solution to the sorting problem is the bubble sort algorithmwhich rearranges the values by iterating over the list multiple timescausing larger values to bubble to the top or end of the list to illustrate how the bubble sort algorithm workssuppose we have four playing cards (all of the same suitthat we want to order from smallest to largest face value we start by laying the cards out face up on table as shown here the algorithm requires multiple passes over the cardswith each pass starting at the first card and ending one card earlier than on the previous iteration during each passthe cards in the first and second positions are compared if the first is larger than the secondthe two cards are swapped nextthe cards in positions two and three are compared if the first one is larger than the secondthey are swapped otherwisewe leave them as they were this process continues for each successive pair of cards until the card with the largest face value is positioned at the end |
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 smallest to largest (pass repeat the process on the first two cards compare the and since is larger than swap the two cards the second largest card ( is now in its ordered position compare the and since is larger than swap the two cards (pass repeat the process on the first three cards compare the and since is less than leave them as is listing provides python implementation of the bubble sort algorithm figure illustrates the swaps performed during the first pass of the algorithm when applied to an array containing integer values figure shows the ordering of the values within the array after each iteration of the outer loop the efficiency of the bubble sort algorithm only depends on the number of keys in the array and is independent of the specific values and the initial arrangement of those values to determine the efficiencywe must determine the total number of iterations performed by the inner loop for sequence containing values the outer loop is executed times since the algorithm makes passes over the sequence the number of iterations for the inner loop is not fixedbut depends on the current iteration of the outer loop on the first pass over the sequencethe inner loop executes timeson the second passn timeson the thirdn timesand so on until it executes once on the last pass the total number |
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 bubblesorttheseq ) lentheseq perform - bubble operations on the sequence for in rangen bubble the largest item to the end for in rangei if theseq[jtheseq[ swap the and + items tmp theseq[jtheseq[jtheseq[ theseq[ tmp |
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 inefficient sorting algorithms due to the total number of swaps required given an array of keys in reverse ordera swap is performed for every iteration of the inner loopwhich can be costly in practice the bubble sort algorithm as implemented in listing always performs iterations of the inner loop but what if the sequence is already in sorted order |
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 sequence is in sorted order we can determine the sequence is in sorted order when no swaps are performed by the if statement within the inner loop at that pointthe function can return immediately without completing the remaining iterations if value is out of sorted orderthen it will either be smaller than its predecessor in the sequence or larger than its successor at which point the condition of the if statement would be true this improvementwhich is left as an exerciseintroduces best case that only requires (ntime when the initial input sequence is in sorted order selection sort second sorting algorithmwhich improves on the bubble sort and works in fashion similar to what human may use to sort list of valuesis known as the selection sort we can again use the set of playing cards to illustrate the algorithm and start by placing five cards face up on table that are to be sorted in ascending order instead of swapping the cards as was done with the bubble sortwe are going to scan through the cards and select the smallest from among those on the table and place it in our hand for our set of cardswe identify the as the smallest we pick up the and place it in our handleaving the remaining cards on the table cards on the table our hand we repeat the process and identify the as the next smallest face value cards on the table |
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 largest pick up the next smallest card ( pick up the next smallest card ( pickup the last card ( the resulting hand the process we used to sort the set of five cards is similar to the approach used by the selection sort algorithm but when implementing insertion sort in codethe algorithm maintains both the sorted and unsorted values within the same sequence structure the selection sortwhich improves on the bubble sortmakes multiple passes over the sequencebut unlike the bubble sortit only makes single swap after each pass the implementation of the selection sort algorithm is provided in listing listing implementation of the selection sort algorithm sorts sequence in ascending order using the selection sort algorithm def selectionsorttheseq ) lentheseq for in rangen )assume the ith element is the smallest smallndx determine if any other element contains smaller value for in rangei )if theseq[jtheseq[smallndxsmallndx swap the ith value and smallndx value only if the smallest value is not already in its proper position some implementations omit testing the condition and always swap the two values if smallndx ! tmp theseq[itheseq[itheseq[smallndxtheseq[smallndxtmp |
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 from those not yet sorted and swapping with the values in the respective positions figure shows the results after each iteration of the algorithm when applied to the sample array of integers the grayed boxes represent those items already placed in their proper position while the black boxes show the two values that are swapped the selection sortwhich makes passes over the array to reposition valuesis also ( the difference between the selection and bubble sorts is that the selection sort reduces the number of swaps required to sort the list to (ninsertion sort another commonly studied sorting algorithm is the insertion sort continuing with our analogy of sorting set of playing cards to illustrate the sorting algorithmsconsider five cards stacked in deck face up the deck we pick up the top card from the deck and place it in our hand our hand the deck since this is the first cardthere is no decision to be made as to its position we again pick up the top card from the deck and compare it to the card already in our hand and insert it into its proper sorted position our hand the deck after placing the into our handthe process is repeated this timewe pick up the and find its position within our hand and insert it in the proper place our hand the deck |
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 items to be sorted in the playing card analogythe deck represents the collection to be sorted and the cards in our hand represents those already sorted when implementing insertion sort in programthe algorithm maintains both the sorted and unsorted collections within the same sequence structure the algorithm keeps the list of sorted values at the front of the sequence and picks the next unsorted value from the first of those yet to be positioned to position the next itemthe correct spot within the sequence of sorted values is found by performing search after finding the proper positionthe slot has to be opened by shifting the items down one position python implementation of the insertion sort algorithm is provided in listing listing implementation of the insertion sort algorithm sorts sequence in ascending order using the insertion sort algorithm def insertionsorttheseq ) lentheseq starts with the first item as the only sorted entry for in range save the value to be positioned value theseq[ifind the position where value fits in the ordered part of the list pos while pos and value theseq[pos shift the items to the right during the search theseq[postheseq[pos pos - put the saved value into the open slot theseq[posvalue the insertionsort(function starts by assuming the first item is in its proper position nextan iteration is performed over the remaining items so each value can be inserted into its proper position within the sorted portion of the sequence the ordered portion of the sequence is at the front while those yet to be inserted are at the end the loop index variable marks the separation point between the two parts the inner loop is used to find the insertion point within the sorted sequence and at the same timeshifts the items down to make room for the next item thusthe inner loop starts from the end of the sorted subsequence and |
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 run times is left as an exercise figure result of applying the insertion sort algorithm to the sample array the gray boxes show values that have been sortedthe black boxes show the next value to be positionedand the lighter gray boxes with black text are the sorted values that have to be shifted to the right to open spot for the next value |
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 typically applied to an unsorted sequence in which all of the values are known and the collection remains static in other wordsno new items will be added to the sequence nor will any be removed in some problemslike the set abstract data typethe collection does not remain static but changes as new items are added and existing ones are removed if sorting algorithm were applied to the underlying list each time new value is added to the setthe result would be highly inefficient since even the best sorting algorithm requires ( log ntime insteadthe sorted list can be maintained as the collection changes by inserting the new item into its proper position without having to re-sort the entire list note that while the sorting algorithms from the previous section all require ( time in the worst casethere are more efficient sorting algorithms (which will be covered in that only require ( log ntime maintaining sorted list to maintain sorted list in real timenew items must be inserted into their proper position the new items cannot simply be appended at the end of the list as they may be out of order insteadwe must locate the proper position within the list and use the insert(method to insert it into the indicated position consider the sorted list from figure if we want to add to that listthen it must be inserted at position following value to find the position of new item within sorted lista modified version of the binary search algorithm can be used the binary search uses divide and conquer strategy to reduce the number of items that must be examined to find target item or to determine the target is not in the list instead of returning true or false indicating the existence of valuewe can modify the algorithm to return the index position of the target if it' actually in the list or where the value should be placed if it were inserted into the list the modified version of the binary search algorithm is shown in listing note the change to the two return statements if the target value is contained in the listit will be found in the same fashion as was done in the original version of the algorithm instead of returning truehoweverthe new version returns its index position when the target is not in the listwe need the algorithm to identify the position where it should be inserted consider the illustration in figure which shows the changes to the three variables lowmidand high as the binary search algorithm progresses in searching for value the while loop terminates when either the low or high range variable crosses the otherresulting in the condition low high upon termination of the loopthe low variable will contain the position where the new value should be placed this index can then be supplied to the insert(method to insert the new |
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 index of the target elif target thelist[midhigh mid else low mid return low index where the target value should be value into the list the findorderedposition(function can also be used with lists containing duplicate valuesbut there is no guarantee where the new value will be placed in relation to the other duplicate values beyond the proper ordering requirement that they be adjacent merging sorted lists sometimes it may be necessary to take two sorted lists and merge them to create new sorted list consider the following code segmentlista listb newlist mergesortedlistslistalistb printnewlist which creates two lists with the items ordered in ascending order and then calls user-defined function to create and return new list created by merging the other two printing the new merged list produces [ problem solution this problem can be solved by simulating the action person might take to merge two stacks of exam paperseach of which are in alphabetical order start by choosing the exam from the two stacks with the name that comes first in alphabetical order flip it over on the table to start new stack againchoose the exam from the top of the two stacks that comes next in alphabetical order and flip it over and place it on top of first one repeat this process until one of the two original stacks is exhausted the exams in the remaining stack can be flipped over on top of the new stack as they are already in alphabetical order and alphabetically follow the |
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 similar approach can be used to merge two sorted lists consider the illustration in figure which demonstrates this process on the sample lists created in the example code segment from earlier the items in the original list are not removedbut instead copied to the new list thusthere is no "topitem from which to select the smallest value as was the case in the example of merging two stacks of exams insteadindex variables are used to indicate the "topor next value within each list the implementation of the mergesortedlists(function is provided in listing the process of merging the two lists begins by creating new empty list and initializing the two index variables to zero loop is used to repeat the process |
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 to the value listb[bthe largest of these two values is added or appended to the new list if the two values are equalthe value from listb is chosen as values are copied from the two original lists to the new merged listone of the two index variables or is incremented to indicate the next largest value in the corresponding list this process is repeated until all of the values have been copied from one of the two listswhich occurs when equals the length of lista or equals the length of listb note that we could have created and initialized the new list with sufficient number of elements to store all of the items from both lista and listb while that works for this specific problemwe want to create more general solution that |
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 appendlista[aa + else newlist appendlistb[bb + if lista contains more itemsappend them to newlist while lenlista newlist appendlista[aa + or if listb contains more itemsappend them to newlist while lenlistb newlist appendlistb[bb + return newlist we can easily modify for similar problems where the new list may not contain all of the items from the other two lists after the first loop terminatesone of the two lists will be empty and one will contain at least one additional value all of the values remaining in that list must be copied to the new merged list this is done by the next two while loopsbut only one will be executed depending on which list contains additional values the position containing the next value to be copied is denoted by the respective index variable or run time analysis to evaluate the solution for merging two sorted listassume lista and listb each contain items the analysis depends on the number of iterations performed by each of the three loopsall of which perform the same action of copying value from one of the two original lists to the new merged list the first loop iterates until all of the values in one of the two original lists have been copied to the third after the first loop terminatesonly one of the next two loops will be executeddepending on which list still contains values the first loop performs the maximum number of iterations when the selection of the next value to be copied alternates between the two lists this results |
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 from one list are copied to the newlist and none from the other if the first loop copies the entire contents of lista to the newlistit will require iterations followed by iterations of the third loop to copy the values from listb if the first loop copies the entire contents of listb to the newlistit will require iterations followed by iterations of the second loop to copy the values from lista in both casesthe three loops are executed for combined total of iterations since the statements performed by each of the three loops all require constant timemerging two lists can be done in (ntime the set adt revisited the implementation of the set adt using list was quick and rather simplebut several of the operations require quadratic time in the worst case this inefficiency is due to the linear search used to find an element in the unsorted list that is required by several of the operations we saw earlier in the the efficiency of the search operation can be improved by using the binary search algorithm to use the binary search with the set adtthe list of elements must be in sorted order and that order must be maintained the definition of the set adthoweverindicates the elements have no particular ordering while this is trueit does not preclude us from storing the elements in sorted order it only means there is no requirement that the items must be stored in particular order sorted list implementation in using the binary search algorithm to improve the efficiency of the set operationsthe list cannot be sorted each time new element is added because it would increase the time-complexity of the add(operation for examplesuppose we used one of the sorting algorithms presented earlier in the to sort the list after each element is added since those algorithms require ( time in the worst casethe add(operation would then also require quadratic time insteadthe sorted order must be maintained when new elements are added by inserting each into its proper position partial implementation of the set adt using sorted list and the binary search algorithm is provided in listing there are no changes needed in the constructor or the len methodbut some changes are needed in the remaining methods |
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__selfelement )ndx self _findpositionelement return ndx lenself and self _theelements[ndx=element adds new unique element to the set def addselfelement )if element not in self ndx self _findpositionelement self _theelements insertndxelement removes an element from the set def removeselfelement )assert element in self"the element must be in the set ndx self _findpositionelement self _theelements popndx determines if this set is subset of setb def issubsetofselfsetb )for element in self if element not in setb return false return true the remaining methods go here returns an iterator for traversing the list of items def __iter__self )return _setiteratorself _theelements finds the position of the element within the ordered list def _findpositionselfelement )low high lenthelist while low <high mid (high low if thelistmid =target return mid elif target thelistmid high mid else low mid return low |
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 there is no need to continue the evaluation of the second component since the overall expression must be false note basic operations performing binary search to locate an element in the sorted list or to find the position where an element belongs in the sorted list is needed in several methods instead of reimplementing the operation each timewe implement the modified version of the binary search algorithm from listing in the findposition(helper method the helper method does not detect nor distinguish between unique and duplicate values it only returns the index where the element is located within the list or where it should be placed if it were added to the list thuscare must be taken when implementing the various methods to check for the existence of an element when necessary the contains method is easily implemented using findposition(the index value returned by the helper method indicates the location where the element should be within the sorted listbut it says nothing about the actual existence of the element to determine if the element is in the setwe can compare the element at the ndx position within the list to the target element note the inclusion of the condition ndx len(selfwithin the compound expression this is needed since the value returned by findposition(can be one larger than the number of items in the listwhich occurs when the target should be located at the end of the list if this value were directly used in examining the contents of the list without making sure it was in rangean out-of-range exception could be raised the contains method has worst case time of (log nsince it uses the binary search to locate the given element within the sorted list to implement the add(methodwe must first determine if the element is unique since set cannot contain duplicate values this is done with the use of the in operatorwhich automatically calls the contains operator method if the element is not already member of the setthe insert(method is called to insert the new element in its proper position within the ordered list even though the contains method has better time-complexity when using sorted list and the binary searchthe add(operation still requires (ntimethe proof of which is left as an exercise the remove(method requires that the target element must be member of the set to verify this preconditionan assertion is made using the in operator after whichthe findposition(helper method is called to obtain the location of the elementwhich can then be used with the pop(list method to remove the element from the underlying sorted list like the add operationthe remove(method still has worst case time of ( )the proof of which is left as an exercise |
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 during which the in operator is applied to setb since the in operator requires (log ntime and it' called timesissubsetof(has time-complexity of ( log na new set equals we could also implement the set equals operation in the same fashion as was done in the original version when using the unsorted listdef __eq__selfsetb )if lenself !lensetb return false else return self issubsetofsetb but that implementation would have time-complexity of ( log nsince it calls the issubsetof(method more efficient implementation of the equals operation is possible if we compare the elements in the list directly instead of using the issubsetof(method rememberfor two sets to be equalthey must contain the exact same elements since the lists for both sets are sortednot only must they contain the same elementsbut those elements must be in corresponding positions within the two lists for the sets to be equal the new implementation of the eq method is provided in listing the two lists are traversed simultaneously during which corresponding elements are compared if single instance occurs where corresponding elements are not identicalthen the two sets cannot be equal otherwisehaving traversed the entire list and finding no mismatched itemsthe two sets must be equal the new implementation only requires (ntime since it only involves one complete traversal of the lists similar approach can be used to improve the efficiency of the issubsetof(method to only require (ntimewhich is left as an exercise listing new implementation of the set equals method class set def __eq__selfsetb )if lenself !lensetb return false else for in rangelen(selfif self _theelements[ !setb _theelements[ireturn false return true |
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 list for the set adt implemented using sorted listthe result of the set union must be new sorted list merged from the unique values contained in the sorted lists used to implement the two source sets the implementation of the new union(methodwhich is provided in listing uses modified version of the mergesortedlists(function the only modification required is the inclusion of an additional test within the first loop to catch any duplicate values by advancing both index variables and only appending one copy to the new sorted list the new implementation only requires (ntime since that is the time required to merge two sorted lists and the new test for duplicates does not increase that complexity the set difference and set intersection operations can also be modified in similar fashion and are left as an exercise listing new implementation of the set union method class set def unionselfsetb )newset set( merge the two lists together until one is empty while lenself and lensetb valuea self _theelements[avalueb setb _theelements[bif valuea valueb newset _theelements appendvaluea + elif valuea valueb newset _theelements appendvalueb + else only one of the two duplicates are appended newset _theelements appendvaluea + + if lista contains more itemsappend them to newlist while lenself newset _theelements appendself _theelements[aa + or if listb contains moreappend them to newlist while lenotherset newset _theelements appendsetb _theelements[bb + return newset |
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 algorithm for locating elements improved the contains method this resulted in better times for the issubsetof(and eq methodsbut the set unionintersectionand difference operations remained quadratic after observing several operations could be further improved if they were implemented to directly access the list instead of using the contains methodwe were able to provide more efficient implementation of the set adt table compares the worst case time-complexities for the set adt operations using an unsorted list and the improved sorted list version using the binary search and the list merging operation operation unordered improved set( ( ( len(so( ( in (no(log ns add(xo(no(ns issubsetof(to( (ns = ( (ns union(to( (ntable comparison of the two set adt implementations using an unsorted list and the improved sorted list with binary search and list merging exercises given an unsorted list of valueswhat is the time-complexity to find the smallest value in the worst casewhat would be the complexity if the list were sorted what is the (*for the findsortedposition(function in the worst case consider the new implementation of the set class using sorted list with the binary search (aprove or show the worst case time for the add(method is ( (bwhat is the best case time for the add(method |
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 values within given list your function should return new list containing the negative values when does the worst case occur and what is the run time for that case in this we used modified version of the mergesortedlists(function to develop linear time union(operation for our set adt implemented using sorted list use similar approach to implement new linear time versions of the issubsetof()intersect()and difference(methods given the following list of keys ( )show the contents of the array after each iteration of the outer loop for the indicated algorithm when sorting in ascending order (abubble sort (bselection sort (cinsertion sort given the following list of keys ( )show the contents of the array after each iteration of the outer loop for the (abubble sort (bselection sort (cinsertion sort evaluate the insertion sort algorithm to determine the best case and the worst case time complexities programming projects implement the bag adt from to use sorted list and the binary search algorithm evaluate the time complexities for each of the operations implement new version of the map adt from section to use sorted list and the binary search algorithm the implementation of the sparse matrix adt from can be improved by storing the matrixelement objects in sorted list and using the binary search to locate specific element the matrix elements can be sorted based on the row and column indices using an index function similar to that used with - array stored in multiarray implement new version of the sparse matrix adt using sorted list and the binary search to locate elements implement new version of the sparse life grid adt from to use sorted list and the binary search to locate the occupied cells |
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 mapping each color in the image that was to be displayed to color in the limited color set specified by the colormap we can define colormap adt for storing limited set of colors and for use in mapping one of the million colors possible in the discrete rgb color space to color in the colormap given the description below of various operationsimplement the colormap adt using - array structure colormapk )creates new empty colormap that is capable of storing up to colors length ()returns the number of colors currently stored in the colormap contains color )determines if the given color is contained in the colormap addcolor )adds the given color to the colormap only one instance of each color can be added to the colormap in additiona color cannot be added to full colormap remove color )removes the given color from the colormap the color must be contained in the colormap in order to be removed mapcolor )maps the given color to an entry in the colormap and returns that color common approach is to map the color to its nearest neighbor in the colormap the nearest neighbor of color is the entry in the colormap that has the minimum euclidean distance squared between the two colors if there is more than one nearest neighbor in the colormaponly one is returned in additionthe colormap must contain at least one color in order to perform the mapping operation iterator ()creates and returns an iterator object that can be used to iterate over the colors in the colormap evaluate the map(method of your implementation of the colormap adt from the previous question to determine the worst case time-complexity colormaps are used in color quantizationwhich is the process of reducing the number of colors in an image while trying to maintain the original appearance as much as possible part of the process recolors an original image using reduced set of colors specified in colormap (aimplement the function recolorimageimagecolormap )which produces new colorimage that results from mapping the color of each pixel in the given image to its nearest neighbor in the given colormap (bwhat is the worst case time-complexity for your implementation |
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 sequence type implemented using an array structure it extends the functionality of an array by providing larger set of operations than the arrayand it can automatically adjust in size as items are added or removed the array and python list can be used to implement many different abstract data types they both store data in linear order and provide easy access to their elements the binary search can be used with both structures when the items are stored in sorted order to allow for quick searches but there are several disadvantages in the use of the array and python list firstinsertion and deletion operations typically require items to be shifted to make room or close gap this can be time consumingespecially for large sequences secondthe size of an array is fixed and cannot change while the python list does provide for an expandable collectionthat expansion does not come without cost since the elements of python list are stored in an arrayan expansion requires the creation of new larger array into which the elements of the original array have to be copied finallythe elements of an array are stored in contiguous bytes of memoryno matter the size of the array each time an array is createdthe program must find and allocate block of memory large enough to store the entire array for large arraysit can be difficult or impossible for the program to locate block of memory into which the array can be stored this is especially true in the case of python list that grows larger during the execution of program since each expansion requires ever larger blocks of memory in this we introduce the linked list data structurewhich is general purpose structure that can be used to store collection in linear order the linked list improves on the construction and management of an array and python list by requiring smaller memory allocations and no element shifts for insertions and |
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 progressone element at timeto the end other variations include the circularly linkedthe doubly linkedand the circularly doubly linked lists introduction suppose we have basic class containing single data fieldclass listnode def __init__selfdata self data data we can create several instances of this classeach storing data of our choosing in the following examplewe create three instanceseach storing an integer valuea listnode listnode listnode the result of which is the creation of three variables and three objects nowsuppose we add second data field to the listnode classclass listnode def __init__selfdata self data data self next none the three objects from the previous example would now have second data field initialized with null referenceas illustrated in the followinga |
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 chain of objectsas illustrated herea we can remove the two external references and by assigning none to eachas shown herea the result is linked list structure the two objects previously pointed to by and are still accessible via for examplesuppose we wanted to print the values of the three objects we can access the other two objects through the next field of the first objectprinta data printa next data printa next next data linked structure contains collection of objects called nodeseach of which contains data and at least one reference or link to another node linked list is linked structure in which the nodes are connected in sequence to form linear |
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 be named or referenced by an external variable as it provides an entry point into the linked list this variable is commonly known as the head pointeror head reference linked list can also be emptywhich is indicated when the head reference is null head figure singly linked list consisting of five nodes and head reference linked structures are built using fundamental components provided by the programming languagenamely reference variables and objects the linked list is just one of several linked structures that we can create if more links are added to each nodeas illustrated in figure we can connect the nodes to form any type of configuration we may need the tree structurewhich organizes the nodes in hierarchical fashionis another commonly used linked structure that we explore later in and entry figure an example of complex linked structure linked list is data structure that can be used to implement any number of abstract data types while some languages do provideas part of their standard librarya generic list adt implemented using linked listwe are going to create and work with linked lists directly some algorithms and abstract data types can be implemented more efficiently if we have direct access to the individual nodes within the adt than would be possible if we created generic linked list class |
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 provide practice in the construction and management of singly linked lists external references we use the term external reference to indicate those reference variables that point to node but are not themselves contained within node as is the case with the link fields some external references must be permanent or exist during the lifetime of the linked list in order to maintain the collection of nodes others are only needed on temporary basis in order to perform specific operation these temporary external references should be local variables that disappear after the function or method has completed note the singly linked list singly linked list is linked list in which each node contains single link field and allows for complete traversal from distinctive first node to the last the linked list in figure is an example of singly linked list there are several operations that are commonly performed on singly linked listwhich we explore in this section to illustrate the implementation of these operationsour code assumes the existence of head reference and uses the listnode class defined earlier the data fields of the listnode class will be accessed directly but this class should not be used outside the module in which it is defined as it is only intended for use by the linked list implementation traversing the nodes in the earlier examplewe accessed the second and third nodes of our sample list by stringing together the next field name off the external reference variable this may be sufficient for lists with few nodesbut it' impractical for large lists insteadwe can use temporary external reference to traverse through the listmoving the reference along as we access the individual nodes the implementation is provided listing the process starts by assigning temporary external reference curnode to point to the first node of the listas illustrated in figure (aafter entering the loopthe value stored in the first node is printed by accessing the data component stored in the node using the external reference the external reference is then advanced to the next node by assigning it the value of the current node' link fieldas illustrated in figure (bthe loop iteration continues until every node in |
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 reference after printing value head curnode (fthe external reference is set to none after printing value head curnode figure traversing linked list requires the initialization and adjustment of temporary external reference variable |
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 the next nodebut there being no next nodecurnode is assigned none from the next field of the last node correct implementation of the linked list traversal must also handle the case where the list is empty rememberan empty list is indicated by null head reference if the list were emptythe curnode reference would be set to null in line of listing and the loop would not execute producing the correct result complete list traversal requires (ntime since each node must be accessed and each access only requires constant time searching for node linear search operation can be performed on linked list it is very similar to the traversal demonstrated earlier the only difference is that the loop can terminate early if we find the target value within the list our implementation of the linear search is illustrated in listing listing searching linked list def unorderedsearchheadtarget )curnode head while curnode is not none and curnode data !target curnodecurnode next return curnode is not none note the order of the two conditions in the while loop it is important that we test for null curnode reference before trying to examine the contents of the node if the item is not found in the listcurnode will be null when the end of the list is reached if we try to evaluate the data field of the null referencean exception will be raisedresulting in run-time error remembera null reference does not point to an object and thus there are no fields or methods to be referenced when implementing the search operation for the linked listwe must make sure it works with both empty and non-empty lists in this casewe do not need separate test to determine if the list is empty this is done automatically by checking the traversal reference variable as the loop condition if the list were emptycurnode would be set to none initially and the loop would never be entered the linked list search operation requires (nin the worst casewhich occurs when the target item is not in the list |
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 constant time since no traversal is required listing prepending node to the linked list given the head pointerprepend an item to an unsorted linked list newnode listnodeitem newnode next head head newnode suppose we want to add the value to our example list shown in figure (aadding an item to the front of the list requires several steps firstwe must create new node to store the new value and then set its next field to point to the node currently at the front of the list we then adjust head to point to the new node since it is now the first node in the list these steps are represented as dashed lines in figure (bnote the order of the new links since it is important we first link the new node into the list before modifying the head reference otherwisewe lose head (ahead newnode (bhead (cfigure prepending node to the linked list(athe original list from figure (blink modifications required to prepend the nodeand (cthe result after prepending |
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 null when the list is empty and the first node inserted needs the next field set to none removing nodes an item can be removed from linked list by removing or unlinking the node containing that item consider the linked list from figure (cand assume we want to remove the node containing firstwe must find the node containing the target value and position an external reference variable pointing to itas illustrated in figure (aafter finding the nodeit has to be unlinked from the listwhich entails adjusting the link field of the node' predecessor to point to its successor as shown in figure (bthe node' link field is also cleared by setting it to none head curnode (ahead curnode ( figure deleting node from linked list(afinding the node to be removed and assigning an external reference variable and (bthe link modifications required to unlink and remove node accessing the node' successor is very simple using the next link of the node but we must also access the node' predecessor in order to change its link the only way we can do this is to position another external reference simultaneously during the search for the given nodeas illustrated in figure (athe result after removing the node containing value is shown in figure (bremoving the first node from the list is special case since the head pointer references this node there is no predecessor that has to be relinkedbut the head reference must be adjusted to point to the next nodeas illustrated in figure |
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 listas illustrated in listing the curnode external reference is initially set to the first node in the listthe same as is done in the traversal and search operations the prednode external reference is set to none since there is no predecessor to the first node in the list loop is used to position the two temporary external reference variables as shown in lines - of listing as the curnode reference is moved along the list in the body of the loopthe prednode reference follows behind thusprednode must be assigned to reference the same node as curnode before advancing curnode to reference the next node after positioning the two external referencesthere are three possible conditions( the item is not in the list( the item is in the first nodeor ( the item is somewhere else in the list if the target is not in the listcurnode will be nullhaving been assigned none via the link field of the last node this condition is evaluated in line to determine if the target is in the first nodewe can simply compare curnode to head and determine if they reference the same node if they dowe set head to point to the next node in the listas shown in lines - pred node head figure modifications required to remove the first node of linked list |
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 elsewhere in the listwe simply adjust the link field of the node referenced by prednode to point to the node following the one referenced by curnode this step is performed in the else clause of the condition as shown in line of listing if the last node is being removedthe same code can be used because the next field of the node pointed to by prednode will be set to none since curnode will be null removing node from linked list requires (ntime since the node could be at the end of the listin which case complete traversal is required to locate the node the bag adt revisited to illustrate the use of the linked list structurewe implement new version of the bag adtwhich we originally defined in section the new implementation is shown in listing on the next page linked list implementation we begin our discussion of the linked list implementation of the bag adt with the constructor firstthe head field will store the head pointer of the linked list the reference is initialized to none to represent an empty bag the size field is used to keep track of the number of items stored in the bag that is needed by the len method technicallythis field is not needed but it does prevent us from having to traverse the list to count the number of nodes each time the length is needed notice we only define head pointer as data field in the object temporary references such as the curnode reference used to traverse the list are not defined as attributesbut instead as local variables within the individual methods as needed sample instance of the new bag class is illustrated in figure the contains(method is simple search of the linked list as described earlier in the the add(method simply implements the prepend operationthough we must also increment the item counter sizeas new items are added the baglistnode classused to represent the individual nodesis also defined |
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__selftarget )curnode self _head while curnode is not none and curnode item !target curnode curnode next return curnode is not none adds new item to the bag def addselfitem )newnode _baglistnodeitem newnode next self _head self _head newnode self _size + removes an instance of the item from the bag def removeselfitem )prednode none curnode self _head while curnode is not none and curnode item !item prednode curnode curnode curnode next the item has to be in the bag to remove it assert curnode is not none"the item must be in the bag unlink the node and return the item self _size - if curnode is head self _head curnode next else prednode next curnode next return curnode item returns an iterator for traversing the list of items def __iter__self )return _bagiteratorself _head defines private storage class for creating list nodes class _baglistnodeobject )def __init__selfitem self item item self next none |
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 that checked the status of the curnode variable has been replaced with an assert statement this was necessary since the remove operation of the bag has precondition that the item must be in the bag in order to be removed if we make it pass the assertionthe item counter is decremented to reflect one less item in the bagthe node containing the item is unlinked from the linked listand the item is returned as required by the adt definition comparing implementations the python list and the linked list can both be used to manage the elements stored in bag both implementations provide the same time-complexities for the various operations with the exception of the add(method when adding an item to bag implemented using python listthe item is appended to the listwhich requires (ntime in the worst case since the underlying array may have to be expanded in the linked list version of the bag adta new bag item is stored in new node that is prepended to the linked structurewhich only requires ( table shows the time-complexities for two implementations of the bag adt in generalthe choice between linked list or python list depends on the application as both have advantages and disadvantages the linked list is typically better choice for those applications involving large amounts of dynamic datadata that changes quite often if there will be large number of insertions and/or deletionsthe linked structure provides fast implementation since large amounts operation python list linked list bag( ( ( len(bo( ( in (no(nb add(xo(no( remove(xo(no(ntraversal (no(ntable comparing the bag adt implemented using python list and linked list |
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 of the listresulting in linear operation whereas the python list only requires constant time linked list iterators suppose we want to provide an iterator for our bag adt implemented using linked list as we did for the one implemented using python list the process would be similarbut our iterator class would have to keep track of the current node in the linked list instead of the current element in the python list we define bag iterator class in listing which would be placed within the llistbag py module that can be used to iterate over the linked list listing an iterator for the bag class implemented using linked list defines linked list iterator for the bag adt class _bagiterator def __init__selflisthead )self _curnode listhead def __iter__self )return self def nextself )if self _curnode is none raise stopiteration else item self _curnode item self _curnode self _curnode next return item when iterating over linked listwe need only keep track of the current node being processed and thus we use single data field curnode in the iterator this reference will be advanced through the linked list as the for loop iterates over the nodes as was done with our python list-based bag classthe linked list version must include the iter method (shown in lines - of listing )which returns an instance of the bagiterator class figure illustrates the bag and bagiterator objects at the beginning of the for loop the curnode pointer in the bagiterator object is used just like the curnode pointer we used when directly performing linked list traversal earlier in the the only difference is that we don' include while loop since python manages the iteration for us as part of the for loop notethe iterator objects can be used with any singly linked list configuration to traverse the nodes and return the data contained in each |
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 basic container in which linear order is not neededsuch as with the bag adt but linked list can also be used to implement container abstract data type that requires specific linear ordering of its elementssuch as with vector adt in additionsome implementationssuch as in the case of the set adtcan be improved if we have access to the end of the list or if the nodes are sorted by element value using tail reference the use of single external reference to point to the head of linked list is sufficient for many applications in some instanceshoweverwe may need to append items to the end of the list instead appending new node to the list using only head reference requires linear time since complete traversal is required to reach the end of the list instead of single external head referencewe can use two external referencesone for the head and one for the tail figure illustrates sample linked list with both head and tail reference head tail figure sample linked list using both head and tail external references appending nodes adding the external tail reference to the linked list requires that we manage both references as nodes are added and removed consider the process of appending new node to non-empty listas illustrated in figure (afirsta new node is created to store the value to be appended to the list thenthe node is linked |
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 reference has to be adjusted to point to the new node since tail must always point to the last node in the list the linked list resulting from appending to the list is illustrated in figure (bif the list is emptythere is no existing node in which the link field can be adjusted insteadboth the head and tail references will be null in this casethe new node is appended to the list by simply adjusting both external references to point to the new node the code for appending node to the linked list is provided in listing it assumes the existence of both the head and tail reference variables listing appending node to linked list using tail reference given the head and tail pointersadds an item to linked list newnode listnodeitem if head is none head newnode else tail next newnode tail newnode removing nodes removing node from linked list in which both head and tail references are used requires simple modification to the code presented earlier in the consider the sample list in figure in which we want to delete the node containing after unlinking the node to be removedwe must check to see if it was at the end |
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 contains single nodethe head reference will be assigned none when it is assigned the contents of the node' next field the tail reference will also be set to none when it is set to prednode listing removing node from linked list using tail reference given the head and tail referencesremoves 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 curnode is tail tail prednode the sorted linked list the items in linked list can be sorted in ascending or descending order as was done with sequence consider the sorted linked list illustrated in figure the sorted list has to be created and maintained as items are added and removed head figure sorted linked list with items in ascending order |
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 listing listing searching sorted linked list def sortedsearchheadtarget curnode head while curnode is not none and curnode data target if curnode data =target return true else curnode node next return false inserting nodes adding new node to an unsorted linked list is simple because we can simply add it to the front or end of the list since its placement is not important when adding node to sorted listhoweverthe correct position for the new value must be found and the new node linked into the list at that position the python implementation for inserting value into sorted linked list is provided in listing as with the removal operation for the unsorted listwe must position two temporary external references by traversing through the linked list searching for the correct position of the new value the only difference is the loop termination condition to insert new nodewe must terminate the loop upon finding the first value larger than the new value being added listing inserting value into sorted list given the head pointerinsert value into sorted linked list find the insertion point for the new value prednode none curnode head while curnode is not none and value curnode data prednode curnode curnode curnode next create the new node for the new value newnode listnodevalue newnode next curnode link the new node into the list if curnode is head head newnode else prednode next newnode |
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 matter where in the list the new node is inserted if the new node is to be inserted in the frontthen the operation is simple prependas was done with an unsorted linked listand curnode will be pointing to the first node when the new value being added is the largest in the list and the new node is to be added at the endcurnode will be null and thus the next field will be null as it should be when the new node is inserted elsewhere in the listcurnode will be pointing to the node that will follow the new node after linking the new node to the listwe must determine if it is being inserted at the front of the listin which case the head reference must be adjusted we do this by comparing the curnode reference with the head reference if they are aliasesthe new node comes first in the linked list and we must adjust the head head newnode - (ahead prednode curnode newnode (bhead prednode curnode newnode (cfigure inserting new value into sorted linked list(ainserting - at the front of the list(binserting in the middle of the list(cinserting at the end of the list |
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 linked list can be used with both sorted and unsorted linked lists since it is not dependent on the contents of the list itself deleting from sorted linked list is the same operation used with an unsorted list with one exception searching for the node containing the target value can end early after encountering the first value larger than the one to be deleted the sparse matrix revisited in the previous we defined and implemented the sparse matrix adt remembera sparse matrix is matrix containing large number of zero elements instead of providing space for every element in the matrixwe need only store the non-zero elements in our original implementationwe used list to store the nonzero elements of the matrixwhich were stored as matrixelement objects this improved the time-complexity of many of the matrix operations when compared to the use of - array we can further improve the sparse matrix adt by using the linked list structure instead of storing the elements in single listhoweverwe can use an array of sorted linked listsone for each row of the matrix the non-zero elements for given row will be stored in the corresponding linked list sorted by column index the row index is not needed since it corresponds to specific linked list within the array of linked lists the sparse matrix from figure is illustrated in figure stored using an array of linked lists listofrows numcols sparsematrix col value next matrixelementnode figure sparse matrix implemented as an array of sorted linked lists |
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 linked lists in which the matrix elements will be stored an array is created whose size is equal to the number of rows in the matrix the individual elements are initialized to none to represent empty linked lists since there are no non-zero elements in the sparse matrix initially note we did not provide field to store the number of rows as that information can be obtained from the length of the array thusnumrows(simply calls the array' length operation the matrixelementnode classprovided in lines - is modified version of the matrixelement class used in the row component has been removed while the next link field was added in order to use the objects as linked nodes when elements are added to the sparse matrixnodes will be added to the individual linked lists based on the row index of the element thusthe row component does not have to be stored in each node changing element values the setitem method is the main linked list management routine for the underlying structure this method not only provides for the modification of element valuesbut it also handles node insertions for new non-zero elements and node removals when an element becomes zero the three operations handled by this method can be combined to produce an efficient implementation the first step is to position the two external reference variables prednode and curnode along the linked list corresponding to the indicated row index while only the curnode reference will be needed for simple element value modificationprednode will be needed if we have to insert new node or remove an existing node after positioning the two referenceswe can then determine what action must be taken if the element corresponding to the given row and col indices is in the linked listcurnode will be pointing to node and the col field of that node will be that of the element in this caseeither the value stored in the node is changed to the new non-zero value or the node has to be deleted when the new value is zero modifying the value only requires changing the value field of the curnode removing the element entry for zero value is also straightforward since the two external references have been positioned correctly and the links can be changed as outlined in section if the element is not represented by node in the linked list of the corresponding row and the new value is non-zerothen new node must be inserted in the proper position based on the prednode and curnode references the only difference in the insertion operation from that used earlier in the is that the head reference is stored in one of the elements of the listofrows array instead of its |
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 the two referencescurnode and prednodewhich require complete list traversal in the worst case since linked list contains single rowwe know it will contain at most nodes listing the llistsparse py module implementation of the sparse matrix adt using an array of linked lists from array import array class sparsematrix creates sparse matrix of size numrows numcols initialized to def __init__selfnumrowsnumcols )self _numcols numcols self _listofrows arraynumrows returns the number of rows in the matrix def numrowsself )return lenself _listofrows returns the number of columns in the matrix def numcolsself )return self _numcols returns the value of element ( , ) [ ,jdef __getitem__selfndxtuple )sets the value of element ( ,jto the value sx[ ,js def __setitem__selfndxtuplevalue )prednode none curnode self _listofrows[rowwhile curnode is not none and curnode col !col prednode curnode curnode curnode next see if the element is in the list if curnode is not none and curnode col =col if value = remove the node if curnode =self _listofrows[rowself _listofrows[rowcurnode next else prednode next curnode next else change the node' value curnode value value otherwisethe element is not in the list elif value ! newnode _matrixelementnodecolvalue newnode next =curnode if curnode =self _listofrows[row |
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 transposeself )matrix additionnewmatrix self rhsmatrix def __add__selfrhsmartrix make sure the two matrices have the correct size assert rhsmatrix numrows(=self numrows(and rhsmatrix numcols(=self numcols()"matrix sizes not compatable for adding create new sparse matrix of the same size newmatrix sparsematrixself numrows()self numcols(add the elements of this matrix to the new matrix for row in rangeself numrows(curnode self _listofrows[rowwhile curnode is not none newmatrix[rowcurnode colcurnode value curnode curnode next add the elements of the rhsmatrix to the new matrix for row in rangerhsmatrix numrows(curnode rhsmatrix _listofrows[rowwhile curnode is not none value newmatrix[rowcurnode colvalue +curnode value newmatrix[rowcurnode colvalue curnode curnode next return the new matrix return newmatrix -matrix subtraction and multiplication --def __sub__selfrhsmatrix def __mul__selfrhsmatrix storage class for creating matrix element nodes class _matrixelementnode def __init__selfcolvalue self col col self value value self next none |
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 sufficient as elements not represented by nodes in the linked lists have zero values and thus would not be affected by scaling factor the matrix scaling operation requires (ktime in the worst case since only the non-zero elements are stored in the structure matrix addition the add method for this version of the sparse matrixwhich is provided in lines - of listing also follows the four steps outlined in section we first create new sparsematrix object that will contain the new matrix resulting from the addition thenthe contents of the self or lefthand-side matrix is copied to the new matrixone element at time finallywe traverse over the non-zero elements of the righthand-side matrix and add the values of its non-zero elements to the new matrix this implementation of the addition operationwhich requires (kntime in the worst caseis not the most efficient instead of using the getitem and setitem operationswe can use temporary traversal reference variables with each matrix to directly access the non-zero values in the two source matrices and to store the resulting non-zero values in the new matrix new implementation can be devised that only requires (ktime in the worst case comparing the implementations the sparse matrix adt implemented as an array of linked lists can be evaluated for any of the three casesbestaverageand worst the analysiswhich is left as an exercisedepends on the relationship between the total number of non-zero elementskand the number of columnsnin the matrix we implemented the matrix adt using - array that can be used to store sparse matrix and we implemented the sparse matrix adt using two different data structuresa list of matrixelement objectsand an array of linked lists table provides comparison of the worst case time-complexities between the three implementations for several of the matrix operations the - array implementation offers the best advantage of quick element access with the getitem and setitem methodsbut the other matrix operations are more costly while both the python list and the array of linked lists implementations provide similar timesthe array of linked lists version will typically provide better times since the efficiency for many of the operations is based on the number of columns in the matrix and not the total number of non-zero elements |
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 arithmetic expressions specified in terms of variables and constants polynomial in one variable can be expressed in expanded form as an xn an- xn- an- xn- where each ai xi component is called term the ai part of the termwhich is scalar that can be zerois called the coefficient of the term the exponent of the xi part is called the degree of that variable and is limited to whole numbers for example consists of three terms the first term is of degree and has coefficient of the second term- xis of degree and has coefficient of - the last termwhile constantis of degree with coefficient of polynomials can be characterized by degree ( all second-degree polynomialsthe degree of polynomial is the largest single degree of its terms the example polynomial above has degree of since the degree of the first term has the largest degree in this sectionwe design and implement an abstract data type to represent polynomials in one variable expressed in expanded form the discussion begins with review of polynomial operations and concludes with linked list implementation of our polynomial adt polynomial operations number of operations can be performed on polynomials we review several of these operationsbeginning with addition |
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 coefficients are subtracted instead another way to view polynomial addition is to align terms by degree and add the corresponding coefficients - - multiplication the product of two polynomials is also third polynomial the new polynomial is obtained by summing the result from multiplying each term of the first polynomial by each term of the second consider the two polynomials from the previous example( )( the second polynomial has to be multiplied by each term of the first polynomial ( ( - ( we then distribute the terms of the first polynomial to yield three intermediate polynomials( ( (- finallythe three polynomials are summedresulting in evaluation the easiest operation by far is the evaluation of polynomial polynomials can be evaluated by assigning value to the variablecommonly called the unknown by making the variable known in specifying valuethe expression can be computedresulting in real value if we assign value to the variable in the equation the result will be ( ) ( ) ( ) ( ) ( |
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 polynomial()creates new polynomial initialized to be empty and thus containing no terms polynomialdegreecoefficient )creates new polynomial initialized with single term constructed from the degree and coefficient arguments degree()returns the degree of the polynomial if the polynomial contains no termsa value of - is returned getitem degree )returns the coefficient for the term of the provided degree thusif the expression of this polynomial is and degree of is providedthis operation returns the coefficient cannot be returned for an empty polynomial evaluatescalar )evaluates the polynomial at the given scalar value and returns the result an empty polynomial cannot be evaluated add rhspolynomial )creates and returns new polynomial that is the result of adding this polynomial and the rhspoly this operation is not defined if either polynomial is empty subtract rhspoly )creates and returns new polynomial that is the result of subtracting this polynomial and the rhspoly this operation is not defined if either polynomial is empty multiply rhspoly )creates and returns new polynomial that is the result of multiplying this polynomial and the rhspoly this operation is not defined if either polynomial is empty two constructors were specified for this abstract data type most objectoriented languages provide mechanism to construct an object in various ways in pythonwe define single constructor and supply default values for the arguments implementation to implement the polynomial adtwe must determine how best to represent the individual terms and how to store and manage the collection of terms in |
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 when working with dynamic polynomials linked list structure we are going to implement our polynomial adt using singly linked list given this choicewe must decide how the data should be stored and organized within the linked list since polynomial is constructed as the sum of one or more non-zero termswe can simply store an individual term in each node of the list as defined by the polytermnode classshown in lines - of listing nextwe must decide whether to order the nodes within the linked list upon analysis of the polynomial operationsit becomes clear an ordered list would be better since many of those operations are based on the degree of the terms for examplethe degree of the polynomial is the degree of the largest term if the list is orderedfinding the polynomial degree is rather simple likewiseyou will soon see that ordering the terms allows for more efficient implementation of the addition and multiplication operations unlike previous exampleswe are going to order the nodes in descending order based on degree since polynomials are typically written with the terms ordered from largest degree to smallest sample linked list structure for the polynomial is illustrated in figure polyhead - - polytail polynomial figure polynomial object for the polynomial finallywe need to decide whether our implementation can benefit from the use of tail pointer or if head pointer alone will suffice rule of thumb in making this decision is whether we will be appending nodes to the list or simply inserting them in their proper position if you need to append nodes to linked listyou should use tail pointer the implementation of some of our polynomial operations can be improved if we append nodes directly to the end of the linked list thuswe will use and manage tail pointer in our implementation of the polynomial adt |
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 _polyhead return the degree of the polynomial def degreeself )if self _polyhead is none return - else return self _polyhead degree return the coefficient for the term of the given degree def __getitem__selfdegree )assert self degree(> "operation not permitted on an empty polynomial curnode self _polyhead while curnode is not none and curnode degree >degree curnode curnode next if curnode is none or curnode degree !degree return else return curnode degree evaluate the polynomial at the given scalar value def evaluateselfscalar )assert self degree(> "only non-empty polynomials can be evaluated result curnode self _polyhead while curnode is not none result +curnode coefficient (scalar *curnode degreecurnode curnode next return result polynomial additionnewpoly self rhspoly def __add__selfrhspoly )polynomial subtractionnewpoly self rhspoly def __sub__selfrhspoly )polynomial multiplicationnewpoly self rhspoly def __mul__selfrhspoly )(listing continued |
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 nodes used with the linked list class _polytermnodeobject )def __init__selfdegreecoefficient )self degree degree self coefficient coefficient self next none basic operations the polynomial adt calls for two constructorsone for creating an empty polynomial and the other that can be used to create polynomial initialized with single term supplied as an argument in pythonwe can provide multiple constructors with the use of default values the constructorshown in lines - of listing defines two data fieldsthe head and tail pointersfor use with the linked list implementation these references are either initialized to none or set to point to the first node in the list depending on how the constructor was called the degree(method is simple to implement as it returns either the degree of the largest term that is stored in the first node or - if the polynomial is not defined for our adta polynomial is not defined if it does not contain any termswhich is indicated in our implementation by an empty list the get operationwhich we implement using the subscript operatorreturns the coefficient corresponding to specific term of the polynomial identified by degree linear search of the linked list is required to find the corresponding term since the nodes are sorted by degreewe can terminate the search early if we encounter node whose degree is smaller than the target after the loop terminatesthere are two possible conditions if there is no non-zero term with the given degreethen curnode will either be none or pointing to list node whose degree is smaller than the target in this casewe must return value of since by definition zero-term has coefficient of otherwisewe simply return the coefficient of the corresponding term pointed to by curnode polynomial is evaluated by supplying specific value for the variable used to represent each term and then summing the terms the evaluate(method is easily implemented as list traversal in which sum is accumulatedterm by term the result is (ntime operationwhere is the degree of the polynomial |
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 by other methods in the class for creating efficient operations the appendterm(helper method in lines - of listing accepts the degree and coefficient of polynomial termcreates new node to store the termand appends the node to the end of the list since we only store the non-zero terms in the linked listwe must ensure the supplied coefficient is not zero before creating and appending the new node polynomial addition the addition of two polynomials can be performed for our linked list implementation using simple brute-force methodas illustrated in the code segment belowclass polynomial def simple_addselfrhspoly )newpoly polynomial(if self degree(rhspoly degree(maxdegree self degree(else maxdegree rhspoly degree( maxdegree while > value self[irhspoly[iself _appendtermivalue + return newpoly the new polynomial is created by iterating over the two original polynomialsterm by termfrom the largest degree among the two polynomials down to degree the element access method is used to extract the coefficients of corresponding terms from each polynomialwhich are then addedresulting in term for the new polynomial since we iterate over the polynomials in decreasing degree orderwe can simply append the new term to the end of the linked list storing the new polynomial this implementation is rather simplebut it' not very efficient the element access methodwhich is used to obtain the coefficientsrequires (ntime assuming the largest degree between the two polynomials is nthe loop will be executed timesresulting in quadratic time in the worst case the polynomial addition operation can be greatly improved upon close examination it becomes clear this problem is similar to that of merging two sorted |
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 listb polyhead polytail merged polyhead polytail figure the top two linked lists store the two polynomials and the bottom list is the resulting polynomial after adding the two original polynomials in we discussed an efficient solution for the problem of merging two sorted lists we also saw how that solution could be used for the set union operationwhich required new python list containing nonduplicate items if we use similar approachcombining duplicate terms by adding their coefficientswe can produce more efficient solution for our current problem of polynomial addition merging two sorted arrays or python listsas was done in the previous is rather simple since we can refer to individual elements by index merging two sorted linked list requires several modifications firstwe must use temporary external references to point to the individual nodes of the two original polynomials these references will be moved along the two linked lists as the terms are processed and merged into the new list nextwe must utilize the appendterm(helper method to append new nodes to the resulting merged list the implementation of the add(method using the list merge technique is provided in listing |
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 is not none and nodeb is not none if nodea degree nodeb degree degree nodea degree value nodea coefficient nodea nodea next elif lista degree listb degree degree nodeb degree value nodeb coefficient nodeb nodeb next else degree nodea degree value nodea coefficient nodeb coefficient nodea nodea next nodeb nodeb next self _appendtermdegreevalue if self list contains more terms append them while nodea is not none self _appendtermnodea degreenodea coefficient nodea nodea next or if rhs contains more terms append them while nodeb is not none self _appendtermnodeb degreenodeb coefficient nodeb nodeb next return newpoly multiplication computing the product of two polynomials requires multiplying the second polynomial by each term in the first this generates series of intermediate polynomialswhich are then added to create the final product to aide in this operationwe create second helper methodtermmultiply()as shown in lines - of listing which creates new polynomial from multiplying an existing polynomial by another term using this helper methodwe can now easily create solution for the multiplication operation that simply implements the individual steps outlined earlier for multiplying two polynomials as with the earlier simple add(methodthis |
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 implementation of the polynomial multiply operation class polynomial def multiplyselfrhspoly )assert self degree(> and rhspoly degree(> "multiplication only allowed on non-empty polynomials create new polynomial by multiplying rhspoly by the first term node self _polyhead newpoly rhspoly _termmultiplynode iterate through the remaining terms of the poly computing the product of the rhspoly by each term node node next while node is not none temppoly rhspoly _termmultiplynode newpoly newpoly addtemppoly node node next return newpoly helper method for creating new polynomial from multiplying an existing polynomial by another term def _termmultiplyselftermnode )newpoly polynomial(iterate through the terms and compute the product of each term and the term in termnode curr curr next while curr is not none compute the product of the term newdegree curr degree termnode degree newcoeff curr coefficient termnode coefficient append it to the new polynomial newpoly _appendtermnewdegreenewcoeff advance the current pointer curr curr next return newpoly |
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 returns the head reference to the head node of the second half of the list if the original list contains single nodenone should be returned evaluate the following code segment which creates singly linked list draw the resulting listincluding the external pointers box none temp none for in range if ! temp listnodei temp next box box temp consider the following singly linked list provide the instructions to insert the new node immediately following the node containing do not use loop or any additional external references head curnode newnode consider the following singly linked list provide the instructions to remove the node containing do not use loop or any additional external references head curnode |
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 ( (cprove or show that the matrix addition operation of the sparsematrix classas implemented in the using an array of sorted linked listshas worst case run time of (kn(das you proved in part ( )the implementation of the sparsematrix add method presented in the is (kna more efficient implementation is possible without the use of the getitem and setitem methods design and implement new version of the add method that has run time of no more than ( (eshow that your implementation of the worst case run time of (kadd method from part(chas (fwhat advantages are there to using sorted linked lists with the sparse matrix adt instead of unsorted linked lists in programming project you implemented the sparse life grid adt that creates game grid of unlimited size for use with the game of life that implementation used single python list to store the individual live cellswhich was similar to the technique we used with the sparse matrix adt explain why the array of linked lists structure used to implement the sparse matrix adt in this cannot be used to implement the sparse life grid adt prove or show that the worst case time for the mul method of the polynomial class implemented in this is ( programming projects we have provided two implementations of the set adt in and (aimplement new version of the set adt using an unsorted linked list (bimplement new version of the set adt using sorted linked list (cevaluate your new implementations to determine the worst case run time of each operation (dcompare the run times of your new versions of the set adt to those from and |
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 are the advantages and disadvantages of using linked list to implement the vector adt consider the map adt from section (aimplement new version of the map adt using an unsorted linked list (bimplement new version of the map adt using sorted linked list (cevaluate your new implementations to determine the worst case run time of each operation (dcompare the run times of your new versions of the map adt to those from section and programming project implement the sub method for the polynomial class implemented in the the implementation of the polynomial mul method is ( in the worst case design and implement more efficient solution for this operation provide new implementation of the polynomial adt to use python list for storing the individual terms integer values are implemented and manipulated at the hardware-levelallowing for fast operations but the hardware does not supported unlimited integer values for examplewhen using -bit architecturethe integers are limited to the range - , , , through , , , if you use -bit architecturethis range is increased to the range - , , , , , , through , , , , , , but what if we need more than digits to represent an integer valuein order to provide platform-independent integers and to support integers larger than digitspython implements its integer type in software that means the storage and all of the operations that can be performed on the values are handled by executable instructions in the program and not by the hardware learning to implement integer values in software offers good example of the need to provide efficient implementations we define the big integer adt below that can be used to store and manipulate integer values of any sizejust like python' built-in int type |
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 be done using any of the logical operators>===!arithmetic rhsint )returns new biginteger object that is the result of performing one of the arithmetic operations on the self and rhsint big integers any of the following operations can be performed/*bitwise-ops rhsint )returns new biginteger object that is the result of performing one of the bitwise operators on the self and rhsint big integers any of the following operations can be performed<>(aimplement the big integer adt using singly linked list in which each digit of the integer value is stored in separate node the nodes should be ordered from the least-significant digit to the largest for examplethe linked list below represents the integer value , head (bimplement the big integer adt using python list for storing the individual digits of an integer modify your implementation of the big integer adt from the previous question by adding the assignment combo operators that can be performed on the self and rhsint big integers allow for any of the following operations to be performed+<<->>*|//&%^** |
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 stacks also occur in our everyday lives consider stack of trays in lunchroom when tray is removed from the topthe others shift up if trays are placed onto the stackthe others are pushed down the stack adt stack is used to store data such that the last item inserted is the first item removed it is used to implement last-in first-out (lifotype protocol the stack is linear data structure in which new items are addedor existing items are removed from the same endcommonly referred to as the top of the stack the opposite end is known as the base consider the example in figure which ( ( ( (dfigure abstract view of stack(apushing value (bpushing value (cresulting stack after and are addedand (dpopping top value |
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 empty stack is one containing no items stack()creates new empty stack isempty()returns boolean value indicating if the stack is empty length ()returns the number of items in the stack pop()removes and returns the top item of the stackif the stack is not empty items cannot be popped from an empty stack the next item on the stack becomes the new top item peek()returns reference to the item on top of non-empty stack without removing it peekingwhich cannot be done on an empty stackdoes not modify the stack contents pushitem )adds the given item to the top of the stack to illustrate simple use of the stack adtwe apply it to the problem of reversing list of integer values the values will be extracted from the user until negative value is enteredwhich flags the end of the collection the values will then be printed in reverse order from how they were entered we could use simple list for this problembut stack is ideal since the values can be pushed onto the stack as they are entered and then popped one at time to print them in reverse order solution for this problem follows prompt "enter an int value (< to end):mystack stack(value int(inputprompt )while value > mystack pushvalue value int(inputprompt )while not mystack isempty(value mystack pop(printvalue suppose the user enters the following valuesone at time - |
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 stackproducing reverse ordering figure resulting stack after executing the sample application implementing the stack the stack adt can be implemented in several ways the two most common approaches in python include the use of python list and linked list the choice depends on the type of application involved using python list the python list-based implementation of the stack adt is the easiest to implement the first decision we have to make when using the list for the stack adt is which end of the list to use as the top and which as the base for the most efficient orderingwe let the end of the list represent the top of the stack and the front represent the base as the stack growsitems are appended to the end of the list and when items are poppedthey are removed from the same end listing on the next page provides the complete implementation of the stack adt using python list the peek(and pop(operations can only be used with non-empty stack since you cannot remove or peek at something that is not there to enforce this requirementwe first assert the stack is not empty before performing the given operation the peek(method simply returns reference to the last item in the list to implement the pop(methodwe call the pop(method of the list structurewhich actually performs the same operation that we are trying to implement that isit saves copy of the last item in the listremoves the item from the listand then returns the saved copy the push(method simply appends new items to the end of the list since that represents the top of our stack |
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 lenself _theitems returns the top item on the stack without removing it def peekself )assert not self isempty()"cannot peek at an empty stackreturn self _theitems[- removes and returns the top item on the stack def popself )assert not self isempty()"cannot pop from an empty stackreturn self _theitems pop(push an item onto the top of the stack def pushselfitem )self _theitems appenditem the individual stack operations are easy to evaluate for the python list-based implementation isempty()len and peek(only require ( time the pop(and push(methods both require (ntime in the worst case since the underlying array used to implement the python list may have to be reallocated to accommodate the addition or removal of the top stack item when used in sequenceboth operations have an amortized cost of ( using linked list the python list-based implementation may not be the best choice for stacks with large number of push and pop operations remembereach append(and pop(list operation may require reallocation of the underlying array used to implement the list singly linked list can be used to implement the stack adtalleviating the concern over array reallocations to use linked listwe again must decide how to represent the stack structure with the python list implementation of the stackit was most efficient to use the end of the list as the top of the stack with linked listhoweverthe front of the list provides the most efficient representation for the top of the stack in we saw how to easily prepend nodes to the linked list as well as remove the first node the stack adt implemented using linked list is provided in listing |
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__self )return self _size returns the top item on the stack without removing it def peekself )assert not self isempty()"cannot peek at an empty stackreturn self _top item removes and returns the top item on the stack def popself )assert not self isempty()"cannot pop from an empty stacknode self _top self top self _top next self _size - return node item pushes an item onto the top of the stack def pushselfitem self _top _stacknodeitemself _top self _size + the private storage class for creating stack nodes class _stacknode def __init__selfitemlink self item item self next link the class constructor creates two instance variables for each stack the top field is the head reference for maintaining the linked list while size is an integer value for keeping track of the number of items on the stack the latter has to be adjusted when items are pushed onto or popped off the stack figure on the next page illustrates sample stack object for the stack from figure (bthe stacknode class is used to create the linked list nodes note the inclusion of the link argument in the constructorwhich is used to initialize the next field of the new node by including this argumentwe can simplify the prepend operation of the push(method the two steps required to prepend node to linked list are combined by passing the head reference top as the second argument of the stacknode(constructor and assigning reference to the new node back to top |
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 operation is only meant to examine the item on top of the stack it should not be used to modify the top item as this would violate the definition of the stack adt the pop(method always removes the first node in the list this operation is illustrated in figure (athis is easy to implement and does not require search to find the node containing specific item the result of the linked list after popping the top item from the stack is illustrated in figure (bthe linked list implementation of the stack adt is more efficient than the python-list based implementation all of the operations are ( in the worst casethe proof of which is left as an exercise size top stack (asize top stack (bfigure popping an item from the stack(athe required link modificationsand (bthe result after popping the top item stack applications the stack adt is required by number of applications encountered in computer science in this sectionwe examine several basic applications that traditionally are presented in data structures course |
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 how the delimiters can be usedwhich includes the requirement of the delimiters being paired and balanced parentheses can be used in mathematical expressions to group or override the order of precedence for various operations to aide in reading complicated expressionsthe writer may choose to use different types of symbol pairsas illustrated here{ ( ( [ ])the delimiters must be used in pairs of corresponding types{}[]and (they must also be positioned such that an opening delimiter within an outer pair must be closed within the same outer pair for examplethe following expression would be invalid since the pair of braces [begin inside the pair of parentheses (but end outside ( [ ){ eanother common use of the three types of braces as delimiters is in the +programming language consider the following code segmentwhich implements function to compute and return the sum of integer values contained in an arrayint sumlistint thelist[]int size int sum int whilei size sum +thelisti ] + return sumas with the arithmetic expressionthe delimiters must be paired and balanced howeverthere are additional rules of the language that dictate the proper placement and use of the symbol pairs we can design and implement an algorithm that scans an input text file containing +source code and determines if the delimiters are properly paired the algorithm will need to remember not only the most recent opening delimiter but also all of the preceding ones in order to match them with closing delimiters in additionthe opening delimiters will need to be remembered in reverse order with the most recent one available first the stack adt is perfect structure for implementing such an algorithm consider the +code segment from earlier as the file is scannedwe can push each opening delimiter onto the stack when closing delimiter is encounteredwe pop the opening delimiter from the stack and compare it to the closing |
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 delimiters are not correct and we can stop processing the file table shows the steps performed by our algorithm and the contents of the stack after each delimiter is encountered in our sample code segment operation stack push push pop match int sumlistint sumlistint valuesint sumlistint values[pop match push current scan line int sumlistint values[]int size int sum int push pop match push push pop match sum +thelisti + pop match pop match whilewhilei size whilei size sum +thelistreturn sumempty table the sequence of steps scanning valid set of delimitersthe operation performed (left columnand the contents of the stack (middle columnas each delimiter is encountered (right columnin the code so farwe have assumed the delimiters are balanced with an equal number of opening and closing delimiters occurring in the proper order but what happens if the delimiters are not balanced and we encounter more opening or closing delimiters than the otherfor examplesuppose the programmer introduced typographical error in the function headerint sumlistint thelist)]int size our algorithm will find the first set of parentheses correct but what happens when the closing bracket is scannedthe result is illustrated in the top part of table you will notice the stack is empty since the left parenthesis was popped |
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 error int sumlistint values)scanningint sumlistint values)]int size operation stack push push push pop match pop match current point of scan int sumlistint sumlistint int sumlistint (valuesint sumlistint values[int sumlistint values[]int size scanningint sumlistint (values[]int size table sequence of steps scanning an invalid set of delimiters the function header(topcontains more closing delimiters than opening and (bottomcontains more closing delimiters than opening delimiters can also be out of balance in the reverse case where there are more opening delimiters than closing ones consider another version of the function headeragain containing typographical errorint sumlistint (thelist[]int size the result of applying our algorithm to this code fragment is illustrated in the bottom chart in table if this were the complete code segmentyou can see we would end up with the stack not being empty since there are opening delimiters yet to be paired with closing ones thusin order to have complete algorithmwe must check for both of these errors python implementation for the validation algorithm is provided in listing the function isvalidsource(accepts file objectwhich we assume was previously opened and contains +source code the file is scanned one line at time and each line is scanned one character at time to determine if it contains properly paired and balanced delimiters stack is used to store the opening delimiters and either implementation can be used since the implementation is independent of the definition herewe have chosen to use the linked list version as the file is scannedwe need only examine |
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 (token ="}and left !"{"or (token ="]and left !"["or (token =")and left !"("return false return isempty(the characters that correspond to one of the three types of delimiter pairs all other characters can be ignored when an opening delimiter is encounteredwe push it onto the stack when closing delimiter occurswe first check to make sure the stack is not empty if it is emptythen the delimiters are not properly paired and balanced and no further processing is needed we terminate the function and return false when the stack is not emptythe top item is popped and compared to the closing delimiter the two delimiters do match corresponding opening and closing delimiterswe again terminate the function and return false finallyafter the entire file is processedthe stack should be empty when the delimiters are properly paired and balanced for the final testwe check to make sure the stack is empty and return either true or falseaccordingly evaluating postfix expressions we work with mathematical expressions on regular basis and they are rather easy for humans to evaluate but the task is more difficult in computer program when an expression is represented as string given the expression we know will be performed firstfollowed by the division and concluding with addition when evaluating this expression stored as string and scanning one character at time from left to righthow do we know the addition has to wait until after the divisionyour first response is probably that we know the order of the precedence for the operators but how do we represent that in our string |
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 ( dwe encounter the division operator and know that the addition is not the first operation to be performed is the division the first operation to be performedit does have higher precedence than the additionbut it may not be the first operation since parentheses can override the order of evaluation we will have to scan more of the string to determine which operation is the first to be performed ( dafter determining the first operation to be performedwe must then decide how to return to those previously skipped this can become tedious process if we have to continuously scanned forward and backward through the string in order to properly evaluate the expression to simplify the evaluation of mathematical expressionwe need an alternative representation for the expression representation in which the order the operators are performed is the order they are specified would allow for single left-to-right scan of the expression string three different notations can be used to represent mathematical expression the most common is the traditional algebraic or infix notation where the operator is specified between the operands + the prefix notation places the operator immediately preceding the two operands +abwhereas in postfix notationthe operator follows the two operands abat first glancethe different notations may seem to be nothing more than different operator placement but the postfix and prefix notations have the advantages that neither uses parentheses to override the order of precedence and both create expressions in unique form in other wordseach expression is unique and produces specific result unlike infix notation in which the same expression can be written in multiple ways converting from infix to postfix infix expressions can be easily converted by hand to postfix notation the expression would be written as ab+cin postfix form the evaluation of this expression would involve first adding and and then subtracting from that result we will examine the evaluation of postfix expressions laterfor now we focus on the conversion from infix to postfix |
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 around every group of operators in the correct order of evaluation there should be one set of parentheses for every operator in the infix expression (( ( ) for each set of parenthesesmove the operator from the middle to the end preceding the corresponding closing parenthesis (( *( /+ remove all of the parenthesesresulting in the equivalent postfix expression compare this result to modified version of the expression in which parentheses are used to place the addition as the first operationa ( cd using the simple algorithmwe parenthesize the expression(( ( )dand move the operators to the end of each parentheses pair(( ( +* /finallyremoving the parentheses yields the postfix expressiona similar algorithm can be used for converting from infix to prefix notation the difference is the operators are moved to the front of each group postfix evaluation algorithm parentheses are used with infix expressions to change the order of evaluation but in postfix notationthe order cannot be altered and thus there is no need for parentheses given the unique form or single order of evaluationpostfix notation is good choice when evaluating mathematical expression represented as string of course the expression would have to either be given in postfix notation or first converted from infix to postfix the latter can be easily done with an appropriate algorithmbut we limit our discussion to the evaluation of existing postfix expressions |
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 character or token at time for each tokenwe perform the following steps if the current item is an operandpush its value onto the stack if the current item is an operator(apop the top two operands off the stack (bperform the operation (note the top value is the right operand while the next to the top value is the left operand (cpush the result of this operation back onto the stack the final result of the expression will be the last value on the stack to illustrate the use of this algorithmlet' evaluate the postfix expression from our earlier example assume the existence of an empty stack and the following variable assignments have been madea the complete sequence of algorithm steps and the contents of the stack after each operation are illustrated in table token alg step abc+* abc+* abc+* abc+* ( pop top two valuesy ( compute or ( abc+*dstack description push value of push value of push value of push result ( of the addition (apop top two valuesy (bcompute or (cpush result ( of the multiplication abc+* abc+* (apop top two valuesy (bcompute or ( push value of push result ( of division table the stack contents and sequence of algorithm steps required to evaluate the valid postfix expression |
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 table what happens if there are too many operators for the given number of operandsconsider such an invalid expressiona in this casethere are too few operands on the stack when we encounter the addition operatoras illustrated in table if we attempt to perform two pops from the stackan assertion error will be thrown since the stack will be empty on the second pop we can modify the algorithm to detect both types of errors in step ( )we must first verify the stack is not empty before popping an item if the stack is emptywe can stop the evaluation and flag an error the second modification occurs after the evaluation of the entire expression we can pop the result from the stack and then verify the stack is empty if the stack is not emptythe expression was invalid and we must flag an error token alg step stack description ab*cd ab*cd ab*cd (apop top two valuesy (bcompute or push value of push value of ( ab*cd ab*cd ab*cd ( pop top two valuesy ( compute or ( error xxxxxx push result ( of the multiplication xxxxxx push value of push value of push result ( of the addition too many values left on stack table the sequence of algorithm steps when evaluating the invalid postfix expression applicationsolving maze classic example of an application that requires the use of stack is the problem of finding path through maze when viewing maze drawn on paper such |
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 as the one illustrated in figure we can quickly find path from the starting point to the exit this usually involves scanning the entire maze and mentally eliminating dead ends but consider human size maze in which you are inside the maze and only have "rat' -eyeview you cannot see over the walls and must travel within the maze remembering where you have been and where you need to go in this situationit' not as easy to find the exit as compared to viewing the maze on paper an algorithm that can be used to find path through maze is likely to employ technique similar to what you would use if you were inside the maze in this sectionwe explore the backtracking technique to solving maze and design an algorithm to implement our technique figure sample maze with the indicated starting (sand exit (epositions backtracking the most basic problem-solving technique in computer science is the brute-force method it involves searching for solution to given problem by systematically trying all possible candidates until either solution is found or it can be determined there is no solution brute-force is time-consuming and is generally chosen as last resort but some problems can only be solved using this technique |
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 likely follow part of the same path from the beginning to some point before we encountered the blocked passage instead of going all the way back to the beginningwe could back up along the path we originally took until we find passage going in different direction we could then follow the new passage in hopes of finding the exit if we again encounter blocked passage before the exitwe can back up one or more steps and try different passage this process of eliminating possible contenders from the solution and partially backing up to try others is known as backtracking and is refinement of the basic brute-force method there is broad class of algorithms that employ this technique and are known as backtracking algorithms all of these algorithms attempt to find solution to problem by extending partial solution one step at time if "dead endis encountered during this processthe algorithm backtracks one or more steps in an attempt to try other possibilities without having to start over from the beginning designing solution the solution to the maze problem is classic example of backtracking in this sectionwe explore the technique and design solution to the maze problem problem details given maze with indicated starting and exit positionsthe objectives are ( determine if there is path from the starting position to the exitand ( specify the path with no circles or loopbacks in designing an algorithm to solve mazeit will be easier if we think of the maze as collection of equal-sized cells laid out in rows and columnsas illustrated in figure the cells will either be filled representing walls of the maze or empty to represent open spaces in additionone cell will be indicated as the starting position and another as the exit figure sample maze from figure divided into equal-sized cells |
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 find path from the start to the exit without ever having to go in circles finallywe limit movement between opens cells to the horizontal and vertical directions--updownleftand right--as illustrated in figure up left right down figure the legal moves allowed from given cell in the maze during our search for the exitwe need to remember which cells have been visited some will be part of the final path to the exit while others will have led us to dead ends at the endwe need to know which cells form the path from the start to the exit but during the search for the exitwe also need to avoid cells that previously led to dead end to assist in remembering the cellswe can place token in each cell visited and distinguish between the two in our examplewe will use an to represent cells along the path and an to represent those that led to dead end describing the algorithm we begin at the starting position and attempt to move from cell to cell until we find the exit as we move between cellswe must consider what actions are available at each cell consider the smaller maze in figure in which the rows and columns have been numbered to aide in identifying the cells figure small maze with the rows and columns labeled for easy reference |
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 orderupdownleftand right in the sample mazewe find the cell above( )is open and prepare to move up one step before moving from the current positionhoweverwe need to lay down token to indicate the current cell is part of our path as indicated earlierwe place lowercase in the cell to indicate it comprises part of the path the complete set of steps taken to solve our sample maze are illustrated in figure after placing the tokenwe move to the open cell above the starting position the current position in the maze is marked in the illustration using an uppercase we repeat the process and find the cell above our current position is open token is laid in the current cell and we move up one position to cell ( from our vantage point above the matrixwe easily see the solution to the problemwhich requires that we move to the right but from the point of view of mouse searching for cheesethat specific move would be unknown using our systematic approachwe examine the cell above our current position we find it openand move up one position to cell ( from this positionwe figure the sequence of steps taken through sample maze is the starting position and is the exit the path is marked using the character while the current cell is marked with cells we visited but from which we had to backtrack are marked with |
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 if it were part of the path since this would cause circle insteadwe mark the cell with different token indicating dead end and move back to the previous position in our examplewe use lowercase to represent cell leading to dead end after moving back to cell ( )we examine the other directions and soon find the cell to the right is open and move in that directionplacing us in cell ( from this positionwe find the only legal move is to the right and thus move in that directionplacing us in cell ( nextwe move up one step since the cell above is open but this move will result in dead endrequiring us to once again back up to the previous position after backing up to our previous position at cell ( )we find the cell below is open and move to position ( repeating the process we soon find the exit at position ( and path from the starting cell to the exit no path to the exit the exit in this example was accessible but what happens if there is no path between the start and exit cellsconsider modified version of our sample maze in figure where wall has been placed in cell ( closing the path to the exit when reaching position ( )as described earlierwe will discover this is dead end and have to back up but there are no other legal moves from cell ( with the positions above and below blocked by wallthe position to the right leading to dead end and the position to the left currently part of our path from position ( )we have to back up and try another direction ultimatelywe will have to backtrack all the way to the starthaving found no legal move from that position figure modified version of the sample maze with the exit blocked the maze adt given the description of the maze problem and the backtracking algorithm for finding path through the mazewe now define the maze adt that can be used to construct and solve maze |
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 cells initialized as open cells the starting and exit positions are undefined numrows()returns the number of rows in the maze numcols()returns the number of columns in the maze setwallrowcol )fills the indicated cell (rowcolwith wall the cell indices must be within the valid range of rows and columns setstartrowcol )sets the indicated cell (rowcolas the starting position the cell indices must be within the valid range setexitrowcol )sets the indicated cell (rowcolas the exit position the cell indices must be within the valid range findpath()attempts to the solve the maze by finding path from the starting position to the exit if solution is foundthe path is marked with tokens (xand true is returned for maze with no solutionfalse is returned and the maze is left in its original state the maze must contain both the starting and exit position cells on the perimeter of the maze can be open and it can be assumed there is an invisible wall surrounding the entire maze reset()resets the maze to its original state by removing any tokens placed during the find path operation draw()prints the maze in readable format using characters to represent the walls and path through the mazeif path has been found both the starting and exit positions are also indicatedif previously set our adt definition is not meant for general purpose mazebut instead one that can be used to build maze and then solve and print the result more general purpose adt would most likely return the solution path as list of tuples instead of simply marking the cells within the maze as is the case in our definition example use we can use this definition of the adt to construct program for building and solving maze as shown in listing the main routine is rather simple since we need only build the mazedetermine if path exists and print the maze if path does exist |
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 size of the maze nrowsncols readvaluepairinfile maze mazenrowsncols read the starting and exit positions rowcol readvaluepairinfile maze setstartrowcol rowcol readvaluepairinfile maze setexitrowcol read the maze itself for row in rangenrows line infile readline(for col in rangelen(lineif line[col="*maze setwallrowcol close the maze file and return the newly constructed maze infile close(return maze extracts an integer value pair from the given input file def readvaluepairinfile )line infile readline(valavalb line split(return int(vala)int(valbcall the main routine to execute the program main(maze text file format before searching for path through the mazewe must first build maze the maze can be constructed directly within the program by calls to setwall(with literal indices or we can read maze specification from text file suppose maze is represented in text file using the following format |
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 blank spaces the maze is constructed from the text file using the buildmaze(function as shown in lines - of listing implementation the implementation of our maze adt will require the selection of data structure to represent the maze and to implement the backtracking operation used to find path the most obvious choice of data structure for storing the maze is - array the individual elements of the array will represent the cells of the maze strings containing single character can be used to represent the walls and tokens while the open cells are easily represented as null pointers the array representation of our sample maze is illustrated in figure figure the abstract view of maze physically represented using - array walls are indicated with an asterisk (*characterwhile open cells contain null reference the start and exit cells will be identified by cell position stored in separate data fields class definition partial implementation of the maze adt is provided in listing three constant class variables are defined and initialized to store the various symbols used to mark cells within the maze rememberclass variables are not data fields of the individual objectsbut are instead variables of the classwhich can be |
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 represent contents of the maze cells maze_wall "*path_token "xtried_token "ocreates maze object with all cells marked as open def __init__selfnumrowsnumcols )self _mazecells array dnumrowsnumcols self _startcell none self _exitcell none returns the number of rows in the maze def numrowsself )return self _mazecells numrows(returns the number of columns in the maze def numcolsself )return self _mazecells numcols(fills the indicated cell with "wallmarker def setwallselfrowcol )assert row > and row self numrows(and col > and col self numcols()"cell index out of range self _mazecells setrowcolself maze_wall sets the starting cell position def setstartselfrowcol )assert row > and row self numrows(and col > and col self numcols()"cell index out of range self _startcell _cellpositionrowcol sets the exit cell position def setexitselfrowcol )assert row > and row self numrows(and col > and col self numcols()"cell index out of range self _exitcell _cellpositionrowcol attempts to solve the maze by finding path from the starting cell to the exit returns true if path is found and false otherwise def findpathself )(listing continued |
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[rowcolis none helper method to determine if the exit was found def _exitfoundselfrowcol )return row =self _exitcell row and col =self _exitcell col drops "triedtoken at the given cell def _marktriedselfrowcol )self _mazecells setrowcolself tried_token drops "pathtoken at the given cell def _markpathselfrowcol )self _mazecells setrowcolself path_token private storage class for holding cell position class _cellpositionobject )def __init__selfrowcol )self row row self col col the class constructorshown in lines - of listing creates multiarray object and two fields to store the starting and exit cells sample maze object for our maze in figure is illustrated in figure the array is created using the arguments to the constructor the cells of the maze are automatically initialized to noneas specified in the previous sectionsince this is the default value used when creating multiarray object the startcell and exitcell fields are set to none since they are initially undefined laterspecific positions will have to be stored when they are defined by the respective methods since cell is indicated by its position within the arraywe can define the cellposition class to store specific cell maze components components of the maze are specified using the various set methodswhich are shown in lines - of listing since the user specifies specific maze elements with each of these methodsthey must first validate the cell position to ensure the |
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 named constants defined earlier helper methods during the actual process of finding solution in the findpath(methodwe will need to perform several routine operations that access the underlying multiarray object to aide in this taskwe define several helper methodsas shown in lines - firstwe will need to drop or place tokens as we move through the maze the marktried(and markpath(methods can be used for this task note we do not need "pickup tokenmethod since the task of picking up path token is immediately followed by dropping tried token the exitfound(method is used to determine if the exit is found based on the contents of the exitcell object and the current position supplied as arguments finallythe validmove(helper method is used to determine if we can move to given cell move is valid if the destination cell is open and its indices are not outside the border of the maze note an assertion is not used here since we do not want to flag an error insteadthe backtracking solution will have to try other directions when encountering an invalid move finding the path tip the findpath(method implements the actual path finding algorithm described earlierwhich searches through the maze for path from the starting position to the helper methods helper methods are commonly used in implementing classes to aide in subdividing larger problems and for reducing code repetition by defining method that can be called from within the different methods but helper methods can also be used to make your code more readable even if they only contain single line this use of helper methods is illustrated by the helper methods defined as part of the maze class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.