id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
13,800 | abstract data types we now turn our attention to selecting data structure for implementing the bag adt the possible candidates at this point include the list and dictionary structures the list can store any type of comparable objectincluding duplicates each item is stored individuallyincluding duplicateswhich means the... |
13,801 | list-based implementation the implementation of the bag adt using list is shown in listing the constructor defines single data fieldwhich is initialized to an empty list this corresponds to the definition of the constructor for the bag adt in which the container is initially created empty sample instance of the bag cla... |
13,802 | abstract data types the implementation of this operation until the next section where we discuss the creation and use of iterators in python list stores references to objects and technically would be illustrated as shown in the figure to the right to conserve space and reduce the clutter that can result in some figures... |
13,803 | designing an iterator to use python' traversal mechanism with our own abstract data typeswe must define an iterator classwhich is class in python containing two special methodsiter and next iterator classes are commonly defined in the same module as the corresponding container class the implementation of the bagiterato... |
13,804 | abstract data types using iterators with the definition of the bagiterator class and the modifications to the bag classwe can now use python' for loop with bag instance when the for loop for item in bag printitem is executedpython automatically calls the iter method on the bag object to create an iterator object figure... |
13,805 | applicationstudent records most computer applications are written to process and manipulate data that is stored external to the program data is commonly extracted from files stored on diskfrom databasesand even from remote sites through web services for examplesuppose we have collection of records stored on disk that c... |
13,806 | abstract data types data from an external file or database in computer programmingan object used to input data into program is sometimes referred to as reader while an object used to output data is referred to as writer define student file reader adt student file reader is used to extract student records from external ... |
13,807 | listing the studentreport py program produces student report from data extracted from an external source from studentfile import studentfilereader name of the file to open file_name "students txtdef main()extract the student records from the given text file reader studentfilereaderfile_name reader open(studentlist read... |
13,808 | abstract data types avoid the use of tuples when storing structured data since it' better practice to use classes with named fields thuswe define the studentrecord class class studentrecord def __init__self )self idnum self firstname none self lastname none self classcode self gpa to store the data related to an indivi... |
13,809 | text file in which the records are listed one after the other the five fields of the record are each stored on separate line the first line contains the id numberthe second and third contain the first and last namesthe fourth line contains the classification codeand the grade point average follows on the fifth line the... |
13,810 | abstract data types listing continued while student !none therecords appendstudent student self fetchrecord(return therecords extract the next student record from the file def fetchrecordself )read the first line of the record line self _inputfile readline(if line ="return none if there is another recordcreate storage ... |
13,811 | and isvalidgregorian(the isvalidgregorian(method should determine if the three components of the given gregorian date are valid add additional operations to the date class(adayofweekname()returns string containing the name of the day (bdayofyear()returns an integer indicating the day of the year for examplethe first da... |
13,812 | abstract data types counting bag adt is just like the bag adt but includes the numof(itemoperationwhich returns the number of occurrences of the given item in the bag implement the counting bag adt and defend your selection of data structure the use of the student file reader adt makes it easy to extract student record... |
13,813 | ispm()determines if this time is post meridiem or after midday (after 'clock nooncomparable othertime )compares this time to the othertime to determine their logical ordering this comparison can be done using any of the python logical operators tostring ()returns string representing the time in the -hour format hh:mm:s... |
13,814 | abstract data types (adefine polygon adt to represent geometric polygon and provide set of appropriate operations (bprovide python implementation of your polygon adt anyone who is involved in many activities typically uses calendar to keep track of the various activities colleges commonly maintain several calendars suc... |
13,815 | arrays the most basic structure for storing and accessing collection of data is the array arrays can be used to solve wide range of problems in computer science most programming languages provide this structured data type as primitive and allow for the creation of arrays with multiple dimensions in this we implement an... |
13,816 | arrays why study arraysyou will notice the array structure looks very similar to python' list structure that' because the two structures are both sequences that are composed of multiple sequential elements that can be accessed by position but there are two major differences between the array and the list firstan array ... |
13,817 | quences we can define the array adt to represent one-dimensional array for use in python that works similarly to arrays found in other languages it will be used throughout the text when an array structure is required define array adt one-dimensional array is collection of contiguous elements in which individual element... |
13,818 | arrays fill the array with random floating-point values for in rangelenvaluelist valuelisti random random(print the valuesone per line for value in valuelist printvalue as second examplesuppose you need to read the contents of text file and count the number of letters occurring in the file with the results printed to t... |
13,819 | syntax for working with the complete functionality available by the underlying hardware that syntaxhowevercan be somewhat cryptic compared to pythonespecially for python programmer who may not be familiar with the ctypes module many of the data types and classes available in python are actually implemented using approp... |
13,820 | arrays an exception would be raised in the same way as if we tried to print the value of variable sumthat had not previously been assigned value thusthe array should be initialized immediately after it has been created by assigning value to each element using the subscript notation any value can be usedbut logical choi... |
13,821 | the size of the array can never changeso removing an item from an array has no effect on the size of the array or on the items stored in other elements the array does not provide any of the list type operations such as appending or popping itemssearching for specific itemor sorting the items to use such an operation wi... |
13,822 | arrays listing continued def __init__selfthearray )self _arrayref thearray self _curndx def __iter__self )return self def __next__self )if self _curndx lenself _arrayref entry self _arrayrefself _curndx self _curndx + return entry else raise stopiteration the constructoras shown in lines - handles the creation and init... |
13,823 | the python list pythonas indicated earlieris built using the language with many of the data types and classes available in python actually implemented using appropriate types available in python' list structure is mutable sequence container that can change size as items are added or removed it is an abstract data type ... |
13,824 | arrays the length of the listobtained using len()is the number of items currently in the subarray and not the size of the underlying array the size or capacity of the array used to implement the list must be maintained in order to know when the array is full python does not provide method to access the capacity value s... |
13,825 | the listthe following steps have to be performed( new array is created with additional capacity( the items from the original array are copied to the new array( the new larger array is set as the data structure for the listand ( the original smaller array is destroyed after the array has been expandedthe value can be ap... |
13,826 | arrays extending list list can be appended to second list using the extend(method as shown in the following examplepylista pylistb pylista extendpylistb if the list being extended has the capacity to store all of the elements from the second listthe elements are simply copiedelement by element if there is not enough ca... |
13,827 | pylist ( pylist ( pylist (cfigure inserting an item into list(athe array elements are shifted to the right one at timetraversing from right to left(bthe new value is then inserted into the array at the given position(cthe result after inserting the item removing items an item can be removed from any position within the... |
13,828 | arrays pylist ( ( pylist (cfigure removing an item from list(aa copy of the item is saved(bthe array elements are shifted to the left one at timetraversing left to rightand (cthe size of the list is decremented by one new list in pythonslicing is performed on list using the colon operator and specifying the beginning e... |
13,829 | two-dimensional arrays arrays are not limited to single dimension some problems require the use of two-dimensional array which organizes data into rows and columns similar to table or grid the individual elements are accessed by specifying two indicesone for the row and one for the column[ ,jfigure shows an abstract vi... |
13,830 | arrays numcols()returns the number of columns in the - array clearvalue )clears the array by setting each element to the given value getitemi )returns the value stored in the - array element at the position indicated by the -tuple ( )both of which must be within the valid range accessed using the subscript operatory [ ... |
13,831 | from array import array open the text file for reading gradefile openfilename"rextract the first two values which indicate the size of the array numexams intgradefile readline(numstudents intgradefile readline(create the - array to store the grades examgrades array dnumstudentsnumexams extract the grades from the remai... |
13,832 | arrays therows array ( (bfigure sample - array(athe abstract view organized into rows and columns and (bthe physical storage of the - array using an array of arrays some languages that use the array of arrays approach for implementing - array provide access to the individual arrays used to store the row elements having... |
13,833 | gets the contents of the element at position [ijdef __getitem__selfndxtuple )assert len(ndxtuple= "invalid number of array subscripts row ndxtuple[ col ndxtuple[ assert row > and row self numrows(and col > and col self numcols()"array subscript out of range the darray self _therows[rowreturn the darray[colsets the cont... |
13,834 | arrays the components in tuple in the order listed within the brackets and passes the tuple to the ndxtuple argument of the getitem method the contents of the ndxtuple are used to extract the contents of the given element after verifying both subscripts are within the valid rangewe extractfrom the data field therowsthe... |
13,835 | numcols()returns the number of columns in the matrix getitem rowcol )returns the value stored in the given matrix element both row and col must be within the valid range setitem rowcolscalar )sets the matrix element at the given row and col to scalar the element indices must be within the valid range scalebyscalar )mul... |
13,836 | arrays multiplication matrix multiplication is only defined for matrices where the number of columns in the matrix on the lefthand side is equal to the number of rows in the matrix on the righthand side the result is new matrix that contains the same number of rows as the matrix on the lefthand side and the same number... |
13,837 | resulting in ( , , , , ( , , , , ( , , , , ( , , , , ( , , , , ( , , , , ( , , , , ( , , , , ( , , , , transpose another useful operation that can be applied to matrix is the matrix transpose given matrixa transpose swaps the rows and columns to create new matrix of size as illustrated here implementing the matrix ther... |
13,838 | arrays listing continued scales the matrix by the given scalar def scalebyselfscalar )for in rangeself numrows(for in rangeself numcols(selfrc *scalar creates and returns new matrix that is the transpose of this matrix def tranposeself )creates and returns new matrix that results from matrix addition def __add__selfrhs... |
13,839 | two given matrices the first step is to ensure the two matrices are the same size as required by the rules of matrix addition after verifying the sizesa new matrix object is created and its elements set by iterating over and summing the corresponding elements from the two sources the new matrix resulting from this oper... |
13,840 | arrays the game starts with an initial configuration supplied by the user successive generations are created by applying the set of rules simultaneously to each cell in the grid interesting patterns can develop as the population of organisms undergoes changes by expanding or eventually dying out to illustrate the game ... |
13,841 | designing solution the game of life requires the use of grid for storing the organisms life grid adt can be defined to add layer of abstraction between the algorithm for "playingthe game and the underlying structure used to store and manipulate the data define life grid adt life grid is used to represent and store the ... |
13,842 | arrays listing the gameoflife py program program for playing the game of life from life import lifegrid define the initial configuration of live cells init_config ( , )( , )( , )( , set the size of the grid grid_width grid_height indicate the number of generations num_gens def main()construct the game grid and configur... |
13,843 | new configuration of organisms based on the rules of the game list is used within evolve(to store the coordinates of live cells in the next generation after iterating over all the cellsthe grid is reconfigured using this list of coordinates this is necessary since the current configuration stored in the game grid canno... |
13,844 | arrays figure the game grid representation with live and dead cells(leftthe abstract view and (rightthe physical view using - array of ' and ' value for the live cells this choice is based on the ease it creates when counting the number of neighbors for given cell figure illustrates the abstract and physical views of t... |
13,845 | is examined the most common is to assume any neighboring cell lying outside the grid contains dead organism listing the life py module implements the lifegrid adt for use with the game of life from array import array class lifegrid defines constants to represent the cell states dead_cell live_cell creates the game grid... |
13,846 | arrays exercises complete the matrix class by implementing the remaining methodsmult and transpose(sub implement the numliveneighbors(method of the lifegrid class complete the implementation of the gameoflife py program by implementing the draw(function the output should look similar to the followingwhere dead cells ar... |
13,847 | as indicated in the when list is created using the replication operator values none the size of the underlying array used to implement the list can be up to twice the size actually needed this extra space is beneficial to the list itselfbut it can be quite wasteful when list is used to implement some abstract data type... |
13,848 | arrays indexofitem )returns the index of the vector element containing the given item the item must be in the list extendothervector )extends this vector by appending the entire contents of the othervector to this vector subvectorfromto )creates and returns new vector that contains subsequence of the items in the vecto... |
13,849 | board divided into squares arranged in rows and columns and set of chips each chip is painted dark color on one side and light color on the otherwith each color belonging to one of the two players the players place their chips on the board and flip the chips of their opponent with the goal of having the most chips of t... |
13,850 | arrays numchipsplayer )returns the number of chips on the board belonging to the indicated player the value of player must be or numopensquares()returns the number of squares still open and available for play getwinner()returns the player number ( or for the player who has won the game or if the game is not finished is... |
13,851 | sets and maps in the previous we studied several complex abstract data types that required the use of data structure for their implementation in this we continue exploring abstract data types with focus on several common containers two of these are provided by python as part of the language itselfsets and dictionaries ... |
13,852 | sets and maps the set abstract data type the definition of the set abstract data type is provided herefollowed by an implementation using list in later we will provide and evaluate alternate implementations for the set adt define set adt set is container that stores collection of unique values over given comparable dom... |
13,853 | iterator ()creates and returns an iterator that can be used to iterate over the collection of items example use to illustrate the use of the set adtwe create and use sets containing the courses currently being taken by two students in the following code segmentwe create two sets and add elements to each the results are... |
13,854 | sets and maps in this casethe two students are both taking csci- and econ- thusthe results of executing the previous code segment will be smith and roberts are taking some of the same coursescsci- econ- suppose we want to know which courses smith is taking that roberts is not taking we can determine this using the set ... |
13,855 | smith theelements set roberts theelements "csci- "csci- set "pol- "pol- "math- "math- "anth- "anth- "hist- "hist- "csci- "csci- "econ- "econ- "econ- "econ- figure two instances of the set class implemented as list listing the linearset py module implementation of the set adt container using python list class set create... |
13,856 | sets and maps listing continued determines if this set is subset of setb def issubsetofselfsetb )for element in self if element not in setb return false return true creates new set from the union of this set and setb def unionselfsetb )newset set(newset _theelements extendself _theelements for element in setb if elemen... |
13,857 | maps avoid reinventing the wheel using operations provided by an adt to implement other methods of that same adt allows you to take advantage of the abstraction and avoid "reinventing the wheelby duplicating code in several places sure the two sets contain the same number of elementsotherwisethey cannot be equal it wou... |
13,858 | sets and maps number to each individual student as illustrated in figure laterwhen the registrar needs to search for student' informationthe identification number is used using this keyed approach allows access to specific student record if the names were used to identify the records insteadthen what happens when multi... |
13,859 | define map adt map is container for storing collection of data records in which each record is associated with unique key the key components must be comparable map()creates new empty map length ()returns the number of key/value pairs in the map contains key )determines if the given key is in the map and returns true if... |
13,860 | sets and maps instead of using two lists to store the key/value entries in the mapwe can use single list the individual keys and corresponding values can both be saved in single objectwith that object then stored in the list sample instance illustrating the data organization required for this approach is shown in figur... |
13,861 | new value replaces the current value associated with the key def addselfkeyvalue )ndx self _findpositionkey if ndx is not none if the key was found self _entrylist[ndxvalue value return false else otherwise add new entry entry _mapentrykeyvalue self _entrylist appendentry return true returns the value associated with t... |
13,862 | sets and maps returns none to indicate the key is not contained in the map when used by the other methodsthe value returned can be evaluated to determine both the existence of the key and the location of the corresponding entry if the key is in the map by combining the two searches into single operationwe eliminate the... |
13,863 | the multiarray abstract data type to accommodate multi-dimensional arrays of two or more dimensionswe define the multiarray adt and as with the earlier array abstract data typeswe limit the operations to those commonly provided by arrays in most programming languages that provide the array structure define multiarray a... |
13,864 | sets and maps appropriate syntax to make use of - array multi-dimensional arrays are not handled at the hardware level insteadthe programming language typically provides its own mechanism for creating and managing multi-dimensional arrays as we saw earliera one-dimensional array is composed of group of sequential eleme... |
13,865 | physical storage of - array using row-major order row row row figure physical storage of sample - array (topin - array using row-major order (bottomindex computation since multi-dimensional arrays are created and managed by instructions in the programming languageaccessing an individual element must also be handled by ... |
13,866 | sets and maps since the subscripts start from zerothe ith subscript not only represents specific row but also indicates the number of complete rows skipped to reach the ith row knowing the position of the first element of each rowthe position for any element within - array can be determined given an element (ijof - arr... |
13,867 | the remaining part of the equation ( is equivalent to index ( )which indicates the number of elements to skip within the table as the number of dimensions increaseadditional products are added to the equationone for each new dimension for examplethe equation to compute the offset for - array is index ( ( ( ( you may no... |
13,868 | sets and maps def func*args )print "number of arguments"lenargs sum for value in args sum +value print"sum of the arguments"sum when using the functionwe can pass variable number of arguments for each invocation for exampleall of the following are valid function callsfunc func func - which results in the following outp... |
13,869 | compute the total number of elements in the array size for in dimensions assert "dimensions must be size * create the - array to store the elements self _elements arraysize create - array to store the equation factors self _factors arraylen(dimensionsself _computefactors(returns the number of dimensions in the array de... |
13,870 | sets and maps constructor the constructorwhich is shown in lines - defines three data fieldsdims stores the sizes of the individual dimensionsfactors stores the factor values used in the index equationand elements is used to store the - array used as the physical storage for the multi-dimensional array the constructor ... |
13,871 | numdims(method returns the dimensionality of the arraywhich can be obtained from the number of elements in the dims tuple element access access to individual elements within an - array requires an -tuple or multicomponent subscriptone for each dimension as indicated in section when multi-component subscript is specifie... |
13,872 | sets and maps lazymart sales report store # item jan feb mar nov dec figure sample sales report where the first line indicates the number of storesthe second line indicates the number of individual items (both of which are integers)and the remaining lines contain the sales data each line of the sales data consists of f... |
13,873 | st or es items months figure the sales data viewed as collection of spreadsheets each spreadsheet contains the sales for specific store and is divided into rows and columns where each row contains the sales for one item and the columns contain the sales for each month since the storeitemand month numbers are all compos... |
13,874 | sets and maps store- accumulate the total sales for the given store total iterate over item for in rangesalesdata length( )iterate over each month of the item for in rangesalesdata length( )total +salesdata[simreturn total assuming our view of the data as collection of spreadsheetsthis requires traversing over every el... |
13,875 | compute the total sales of single item in all stores over all months def totalsalesbyitemsalesdataitem )the item number must be offset by item accumulate the total sales for the given month total iterate over each store for in rangesalesdata length( )iterate over each month of the store for in rangesalesdata length( )t... |
13,876 | sets and maps compute the total sales per month for given store - array is returned that contains the totals for each month def totalsalespermonthsalesdatastore )the store number must be offset by store the totals will be returned in - array totals array iterate over the sales of each month for in rangesalesdata length... |
13,877 | exercises complete the set adt by implementing intersect(and difference( modify the set(constructor to accept an optional variable argument to which collection of initial values can be passed to initialize the set the prototype for the new constructor should look as followsdef setself*initelements none it can then be u... |
13,878 | sets and maps design and implement the iterator class mapiterator for use with the map adt implemented using list develop the index equation that computes the location within - array for element (ijof - array stored in column-major order the - array described in is simple rectangular structure consisting of the same nu... |
13,879 | algorithm analysis algorithms are designed to solve problemsbut given problem can have many different solutions how then are we to determine which solution is the most efficient for given problemone approach is to measure the execution time we can implement the solution by constructing computer programusing given progr... |
13,880 | algorithm analysis suppose we want to analyze the algorithm based on the number of additions performed in this examplethere are only two addition operationsmaking this simple task the algorithm contains two loopsone nested inside the other the inner loop is executed times and since it contains the two addition operatio... |
13,881 | figure graphical comparison of the growth rates from table big- notation instead of counting the precise number of operations or stepscomputer scientists are more interested in classifying an algorithm based on the order of magnitude as applied to execution time or space requirements this classification approximates th... |
13,882 | algorithm analysis function (nindicates the rate of growth at which the run time of an algorithm increases as the input sizenincreases to specify the time-complexity of an algorithmwhich runs on the order of ( )we use the notation of (nconsider the two versions of our algorithm from earlier for version onethe time was ... |
13,883 | , , , , , , , , , , , table numerical comparison of two sample algorithms figure graphical comparison of the data from table operations required by an algorithm can be computed as sum of the times required to perform each stept (nf (nf (nfk (nthe steps requiring constant time are generally omitted since they eventually... |
13,884 | algorithm analysis totalsum for in rangen rowsum[ (an (bfor in rangen rowsum[irowsum[imatrix[ ,jtotalsum totalsum matrix[ , for in rangen for in rangen figure markup for version one of the matrix summing algorithm(ashows all operations marked with the appropriate time and (bshows only the non-constant time steps choosi... |
13,885 | (*common name constant log logarithmic linear log log linear quadratic cubic an exponential table common big- functions listed from smallest to largest order of magnitude log log figure growth rates of the common time-complexity functions any algorithm whose time-complexity is (loga nthese algorithms are generally very... |
13,886 | algorithm analysis are characterized by time-complexity of (nm since the dominant term is the highest power of the most common polynomial algorithms are linear ( )quadratic ( )and cubic ( an algorithm whose efficiency is characterized by dominant term in the form an is called exponential exponential algorithms are amon... |
13,887 | efficiency of string operations most of the string operations have time-complexity that is proportional to the length of the string for most problems that do not involve string processingstring operations seldom have an impact on the run time of an algorithm thusin the textwe assume the string operationsincluding the u... |
13,888 | algorithm analysis both loops will be executed nbut since the inner loop is nested inside the outer loopthe total time required by the outer loop will be (nn nresulting in time of ( for the ex (function not all nested loops result in quadratic time consider the following functiondef ex )count for in rangen for in range... |
13,889 | count + / return count to determine the run time of this functionwe have to determine the number of loop iterations just like we did with the earlier examples since the loop variable is cut in half each timethis will be less than for exampleif equals variable will contain the following five values during subsequent ite... |
13,890 | algorithm analysis at first glanceit appears the loop will execute timeswhere is the size of the list but notice the return statement inside the loopwhich can cause it to terminate early if the list does not contain negative valuel findnegl the return statement inside the loop will not be executed and the loop will ter... |
13,891 | list operation worst case list( ( (nv[ix ( append(xo(nv extend(wo(nv insert(xo(nv pop( (ntraversal (ntable worst case time-complexities for the more common list operations list traversal sequence traversal accesses the individual itemsone after the otherin order to perform some operation on every item python provides t... |
13,892 | algorithm analysis create listtemp list(valuelist the first example creates an empty listwhich can be accomplished in constant time the second creates list containing elementswith each element initialized to the actual allocation of the elements can be done in constant timebut the initialization of the individual eleme... |
13,893 | amortized cost the append(operation of the list structure introduces special case in algorithm analysis the time required depends on the available capacity of the underlying array used to implement the list if there are available slotsa value can be appended to the list in constant time if the array has to be expanded ... |
13,894 | algorithm analysis si ei size list contents table using the aggregate method to compute the total run time for sequence of append operations vary in which many of the operations in the sequence contribute little cost and only few operations contribute high cost to the overall time this is exactly the case with the appe... |
13,895 | evaluating the set adt we can use complexity analysis to determine the efficiency of the set adt operations as implemented in section for conveniencethe relevant portions of that implementation are shown again in listing on the next page the evaluation is quite simple since the adt was implemented using the list and we... |
13,896 | algorithm analysis listing partial listing of the linearset py module from listing class set def __init__self )self _theelements list(def __len__self )return lenself _theelements def __contains__selfelement )return element in self _theelements def addselfelement )if element not in self self _theelements appendelement d... |
13,897 | is member of set if the element is not member of set ait' added to set by applying the append(list method we know from earlier the linear search performed by the in operator requires (ntime and we can use the ( amortized cost of the append(method since it is applied in sequence given that the loop is performed times an... |
13,898 | algorithm analysis listing the sparsematrix py module implementation of the sparse matrix adt using list class sparsematrix create sparse matrix of size numrows numcols initialized to def __init__selfnumrowsnumcols )self _numrows numrows self _numcols numcols self _elementlist list(return the number of rows in the matr... |
13,899 | storage class for holding the non-zero matrix elements class _matrixelementdef __init__selfrowcolvalue )self row row self col col self value value constructor the constructor defines three attributes for storing the data related to the sparse matrix the elementlist field stores matrixelement objects representing the no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.