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 reference to each individual object is stored and later accessible when needed this satisfies the storage requirements of the bag adtmaking the list candidate structure for its implementation the dictionary stores key/value pairs in which the key component must be comparable and unique to use the dictionary in implementing the bag adtwe must have way to store duplicate items as required by the definition of the abstract data type to accomplish thiseach unique item can be stored in the key part of the key/value pair and counter can be stored in the value part the counter would be used to indicate the number of occurrences of the corresponding item in the bag when duplicate item is addedthe counter is incrementedwhen duplicate is removedthe counter is decremented both the list and dictionary structures could be used to implement the bag adt for the simple version of the baghoweverthe list is better choice since the dictionary would require twice as much space to store the contents of the bag in the case where most of the items are unique the dictionary is an excellent choice for the implementation of the counting bag variation of the adt having chosen the listwe must ensure it provides the means to implement the complete set of bag operations when implementing an adtwe must use the functionality provided by the underlying data structure sometimesan adt operation is identical to one already provided by the data structure in this casethe implementation can be quite simple and may consist of single call to the corresponding operation of the structurewhile in other caseswe have to use multiple operations provided by the structure to help verify correct implementation of the bag adt using the listwe can outline how each bag operation will be implementedan empty bag can be represented by an empty list the size of the bag can be determined by the size of the list determining if the bag contains specific item can be done using the equivalent list operation when new item is added to the bagit can be appended to the end of the list since there is no specific ordering of the items in bag removing an item from the bag can also be handled by the equivalent list operation the items in list can be traversed using for loop and python provides for user-defined iterators that be used with bag from this itemized listwe see that each bag adt operation can be implemented using the available functionality of the list thusthe list is suitable for implementing the bag |
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 class created from the example checkdates py program provided earlier is illustrated in figure listing the linearbag py module implements the bag adt container using python list class bag constructs an empty bag def __init__self )self _theitems list(returns the number of items in the bag def __len__self )return lenself _theitems determines if an item is contained in the bag def __contains__selfitem )return item in self _theitems adds new item to the bag def addselfitem )self _theitems appenditem removes and returns an instance of the item from the bag def removeselfitem )assert item in self _theitems"the item must be in the bag ndx self _theitems indexitem return self _theitems popndx returns an iterator for traversing the list of items def __iter__selfitem )most of the implementation details follow the specifics discussed in the previous section there are some additional detailshowever firstthe adt definition of the remove(operation specifies the precondition that the item must exist in the bag in order to be removed thuswe must first assert that condition and verify the existence of the item secondwe need to provide an iteration mechanism that allows us to iterate over the individual items in the bag we delay theitems bag figure sample instance of the bag class implemented using list |
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 figureshoweverwe illustrate objects in the text as boxes with rounded edges and show them stored directly bag within the list structure variables theitems will be illustrated as square boxes bag with bullet in the middle and the name of the variable printed nearby bag iterators traversals are very common operationsespecially on containers traversal iterates over the entire collectionproviding access to each individual element traversals can be used for number of operationsincluding searching for specific item or printing an entire collection python' container types--stringstupleslistsand dictionaries--can be traversed using the for loop construct for our user-defined abstract data typeswe can add methods that perform specific traversal operations when necessary for exampleif we wanted to save every item contained in bag to text filewe could add saveelements(method that traverses over the vector and writes each value to file but this would limit the format of the resulting text file to that specified in the new method in addition to saving the itemsperhaps we would like to simply print the items to the screen in specific way to perform the latterwe would have to add yet another operation to our adt not all abstract data types should provide traversal operationbut it is appropriate for most container types thuswe need way to allow generic traversals to be performed one way would be to provide the user with access to the underlying data structure used to implement the adt but this would violate the abstraction principle and defeat the purpose of defining new abstract data types pythonlike many of today' object-oriented languagesprovides built-in iterator construct that can be used to perform traversals on user-defined adts an iterator is an object that provides mechanism for performing generic traversals through container without having to expose the underlying implementation iterators are used with python' for loop construct to provide traversal mechanism for both built-in and user-defined containers consider the code segment from the checkdates py program in section that uses the for loop to traverse the collection of datesiterate over the bag and check the ages for date in bag if date <bornbefore print"is at least years of age"date |
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 bagiterator class is shown in listing the constructor defines two data fields one is an alias to the list used to store the items in the bagand the other is loop index variable that will be used to iterate over that list the loop variable is initialized to zero in order to start from the beginning of the list the iter method simply returns reference to the object itself and is always implemented to do so listing the bagiterator classwhich is part of the linearbag py module an iterator for the bag adt implemented as python list class _bagiterator def __init__selfthelist )self _bagitems thelist self _curitem def __iter__self )return self def __next__self )if self _curitem lenself _bagitems item self _bagitemsself _curitem self _curitem + return item else raise stopiteration the next method is called to return the next item in the container the method first saves reference to the current item indicated by the loop variable the loop variable is then incremented by one to prepare it for the next invocation of the next method if there are no additional itemsthe method must raise stopiteration exception that flags the for loop to terminate finallywe must add an iter method to our bag classas shown heredef __iter__self )return _bagiteratorself _theitems this methodwhich is responsible for creating and returning an instance of the bagiterator classis automatically called at the beginning of the for loop to create an iterator object for use with the loop construct |
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 illustrates the state of the bagiterator object immediately after being created notice the bagitems field of the iterator object references theitems field of the bag object this reference was assigned by the constructor when the bagiterator object was created bagvectorcuritem curitem _bagiterator theitems bag figure the bag and bagiterator objects before the first loop iteration the for loop then automatically calls the next method on the iterator object to access the next item in the container the state of the iterator object changes with the curitem field having been incremented by one this process continues until stopiteration exception is raised by the next method when the items have been exhausted as indicated by the curitem after all of the items have been processedthe iteration is terminated and execution continues with the next statement following the loop the following code segment illustrates how python actually performs the iteration when for loop is used with an instance of the bag classcreate bagiterator object for mybag iterator mybag __iter__(repeat the while loop until break is called while true tryget the next item from the bag if there are no more itemsthe stopiteration exception is raised item iterator __next__(perform the body of the for loop printitem catch the exception and break from the loop when we are done except stopiterationbreak |
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 contain information related to students at smalltown college we have been assigned the task to extract this information and produce report similar to the following in which the records are sorted by identification number list of students id name class gpa --- smithjohn sophomore joneswendy junior smithjane senior walessam senior robertssally freshman greenpatrick freshman nelsonamy sophomore robertsjane senior taylorsusan sophomore loganmark junior brownjessica sophomore number of students our contact in the registrar' officewho assigned the taskhas provided some information about the data we know each record contains five pieces of information for an individual student( the student' id number represented as an integer( their first and last nameswhich are strings( an integer classification code in the range [ that indicates if the student is freshmansophomorejunioror seniorand ( their current grade point average represented as floatingpoint value what we have not been toldhoweveris how the data is stored on disk it could be stored in plain text filein binary fileor even in database in additionif the data is stored in text or binary filewe will need to know how the data is formatted in the fileand if it' in relational databasewe will need to know the type and the structure of the database designing solution even though we have not yet been told the type of file or the format used to store the datawe can begin designing and implementing solution by working with an abstraction of the input source no matter the source or format of the datathe extraction of data records from external storage requires similar stepsopen connectionextract the individual recordsthen close the connection to aide in our effortwe define student file reader adt to represent the extraction of |
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 storage the five data components of the individual records are extracted and stored in storage object specific for this collection of student records studentfilereaderfilename )creates student reader instance for extracting student records from the given file the type and format of the file is dependent on the specific implementation open()opens connection to the input source and prepares it for extracting student records if connection cannot be openedan exception is raised close()closes the connection to the input source if the connection is not currently openan exception is raised fetchrecord()extracts the next student record from the input source and returns reference to storage object containing the data none is returned when there are no additional records to be extracted an exception is raised if the connection to the input source was previously closed fetchall()the same as fetchrecord()but extracts all student records (or those remainingfrom the input source and returns them in python list creating the report the program in listing uses the student file reader adt to produce the sample report illustrated earlier the program extracts the student records from the input sourcesorts the records by student identification numberand produces the report this program illustrates some of the advantages of applying abstraction to problem solving by focusing on the "whatinstead of the "how by using the student file reader adtwe are able to design solution and construct program for the problem at hand without knowing exactly how the data is stored in the external source we import the studentfilereader class from the studentfile py modulewhich we assume will be an implementation of the adt that handles the actual data extraction furtherif we want to use this same program with data file having different formatthe only modifications required will be to indicate different module in the import statement and possibly change to the filename specified by the constant variable file name the studentreport py program consists of two functionsprintreport(and main(the main routine uses an instance of the adt to connect to the external source in order to extract the student records into list the list of records is then |
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 reader fetchall(reader close(sort the list by id number each object is passed to the lambda expression which returns the idnum field of the object studentlist sortkey lambda recrec idnum print the student report printreportstudentlist prints the student report def printreportthelist )the class names associated with the class codes classnames none"freshman""sophomore""junior""seniorprint the header print"list of studentscenter( print"print"%- %- %- %- ('id''name''class''gpaprint"% % % % ('- '- '- '- )print the body for record in thelist print"% %- %- % (record idnumrecord lastname 'record firstnameclassnames[record classcode]record gpaadd footer print"- print"number of students:"len(thelistexecutes the main routine main(sorted in ascending order based on the student identification number the actual report is produced by passing the sorted list to the printreport(function storage class when the data for an individual student is extracted from the input fileit will need to be saved in storage object that can be added to list in order to first sort and then print the records we could use tuples to store the recordsbut we |
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 individual student you may notice there is only constructor with no additional methods this is complete class as defined and represents storage class the constructor is all that' needed to define the two data fields for storing the two component values storage classes should be defined within the same module as the class with which they will be used for this applicationthe studentrecord class is defined at the end of the studentfile py module some storage classes may be intended for internal use by specific class and not meant to be accessed from outside the module in those casesthe name of the storage class will begin with single underscorewhich flags it as being private to the module in which it' defined the studentrecord classhoweverhas not been defined as being private to the module since instances of the storage class are not confined to the adt but instead are returned to the client code by methods of the studentfilereader class the storage class can be imported along with the studentfilereader class when needed you will note the data fields in the storage class are public (by our notationsince their names do not begin with an underscore as they have been in other classes presented earlier the reason we do not include restrictive interface for accessing the data fields is that storage objects are meant to be used exclusively for storing data and not as an instance of some abstract data type given their limited usewe access the data fields directly as needed implementation the implementation of the student file reader adt does not require data structure since it does not store data but instead extracts data from an external source the adt has to be implemented to extract data based on the format in which the data is stored for this examplewe are going to extract the data from caution python tuples the tuple can be used to store structured datawith each element corresponding to an individual data field this is not good practicehoweversince the elements are not named and you would have to remember what piece of data is stored in each element better practice is to use objects with named data fields in this bookwe limit the use of tuples for returning multiple values from methods and functions |
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 following text block illustrates the format for file containing two records john smith jane roberts listing provides the implementation of the adt for extracting the records from the text file in the given format the constructor simply initializes an instance of the class by creating two attributesone to store the name the text file and the other to store reference to the file object after it' opened the open(method is responsible for opening the input file using the name saved in the constructor the resulting file object is saved in the inputfile attribute so it can be used in the other methods after the records are extractedthe file is closed by calling the close(method listing the studentfile py module implementation of the studentfilereader adt using text file as the input source in which each field is stored on separate line class studentfilereader create new student reader instance def __init__selfinputsrc )self _inputsrc inputsrc self _inputfile none open connection to the input file def openself )self _inputfile openself _inputsrc"rclose the connection to the input file def closeself )self _inputfile close(self _inputfile none extract all student records and store them in list def fetchallself )therecords list(student self fetchrecord((listing continued |
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 object and fill it student studentrecord(student idnum intline student firstname self _inputfile readline(rstrip(student lastname self _inputfile readline(rstrip(student classcode intself _inputfile readline(student gpa floatself _inputfile readline(return student storage class used for an individual student record class studentrecord def __init__self )self idnum self firstname none self lastname none self classcode self gpa the fetchall(methodat lines - is simple event-controlled loop that builds and returns list of studentrecord objects this is done by repeatedly calling the fetchrecord(method thusthe actual extraction of record from the text file is handled by the fetchrecord(methodas shown in lines - to extract the student records from file in which the data is stored in different formatwe need only modify this method to accommodate the new format the student file reader adt provides framework that can be used to extract any type of records from text file the only change required would be in the fetchrecord(method to create the appropriate storage object and to extract the data from the file in the given format exercises complete the partial implementation of the date class by implementing the remaining methodsmonthname()isleapyear()numdays()advanceby() |
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 day of february is day of the year (cisweekday()determines if the date is weekday (disequinox()determines if the date is the spring or autumn equinox (eissolstice()determines if the date is the summer or winter solstice (fasgregorian(divchar '/')similar to the str(method but uses the optional argument divchar as the dividing character between the three components of the gregorian date implement function named printcalendar(that accepts date object and prints calendar for the month of the given date for exampleif the date object passed to the function contained the date the function should print su november mo tu we th fr sa modify the date(constructor to make each of the three arguments optionalwith an initial value of zero when no argument is supplied to the constructorthe object should be initialized to the current date hintyou will need to use python' date(function from the time py module programming projects click counter is small hand-held device that contains push button and count display to increment the counterthe button is pushed and the new count shows in the display clicker counters also contain button that can be pressed to reset the counter to zero design and implement the counter adt that functions as hand-held clicker grab bag adt is similar to the bag adt with one difference grab bag does not have remove(operationbut in place of it has grabitem(operationwhich allows for the random removal of an item from the bag implement the grab bag adt |
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 records from text file no matter the format used to store the data implement new version of the adt to extract the data from text file in which each record is stored on separate line and the individual fields are separated by commas for examplethe following illustrates the format of sample file containing three student records johnsmith janeroberts patrickgreen in the we defined and implemented the student file reader adt for extracting student records from an external source we can define and use similar adt for output (adesign student file writer adt that can be used to displayor store to an output devicestudent records contained in studentrecord object (bprovide an implementation of your adt to output the records by displaying them to the terminal in neatly formatted fashion (cprovide an implementation of your adt to output the records to text file using the same format described in the text (ddesign and implement complete program that extracts student records from text filesorts them by either student id or student nameand displays them to the terminal using your adt the choice of sort keys should be extracted from the user we can use time adt to represent the time of dayfor any -hour periodas the number of seconds that have elapsed since midnight given the following list of operationsimplement the time adt timehoursminutesseconds )creates new time instance and initializes it with the given time hour()returns the hour part of the time minutes()returns the minutes part of the time seconds()returns the seconds part of the time numsecondsothertime )returns the number of seconds as positive integer between this time and the othertime isam()determines if this time is ante meridiem or before midday (at or before 'clock noon |
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:ss invoked by calling python' str(constructor design and implement timedate adt that can be used to represent both date and time as single entity line segment is straight line bounded by two endpoints the line segment adtwhose operations are described belowrepresents line segment defined by points in the two-dimensional cartesian coordinate system use the point class from appendix and implement the line segment adt linesegmentptaptb )creates new line segment instance defined by the two point objects endpointa()returns the first endpoint of the line endpointb()returns the second endpoint of the line length ()returns the length of the line segment given as the euclidean distance between the two endpoints tostring ()returns string representation of the line segment in the format (axay)#(bxbyisvertical()is the line segment parallel to the -axisishorizontal()is the line segment parallel to the -axisisparallelotherline )is this line segment parallel to the otherlineisperpendicularotherline )is this line segment perpendicular to the otherlineintersects(otherline )does this line segment intersect the otherlinebisectsotherline )does this line segment bisect the otherlineslope()returns the slope of the line segment given as the rise over the run if the line segment is verticalnone is returned shiftxincyinc )shifts the line segment by xinc amount along the -axis and yinc amount along the -axis midpoint()returns the midpoint of the line segment as point object polygon is closed geometric shape consisting of three or more line segments that are connected end to end the endpoints of the line segments are known as verticeswhich can be defined by points in the two-dimensional cartesian coordinate system |
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 such as an academic calendara school events calendarand sporting events calendar we have defined an activities calendar adt below that can keep track of one activity per day over given range of dates select data structure and implement the adt activitiescalendardatefromdateto )creates new empty activities calendar initialized to the given range of dates the date range can be specified for any non-overlapping period the only requirements are that datefrom must precede dateto and dateto cannot overlap the day and month of datefrom for the next year length ()returns the number of activities on the calendar getactivitydate )returns the string that describes the activity for the given date if an activity exists for the given dateotherwisenone is returned addactivitydateactivity )adds the given activity description to the calendar for the given date the date must be within the valid date range for the calendar displaymonthmonth )displays to standard output all activities for the given month the display includes the year and name of the month and the list of activities for the month the display of each activity includes the day of the month on which the activity occurs and the description of the activity python provides numeric class for working with floating-point values but not all real numbers can be represented precisely on computer since they are stored as binary values in applications where the precision of real numbers is importantwe can use rational numbers or fractions to store exact values fractionsuch as consists of two partsboth of which are integers the top valuewhich can be any integer valueis known as the numerator the bottom valuewhich must be greater than zerois known as the denominator (adefine fraction adt to represent and store rational numbers the adt should include all of the common mathematical and logical operations in additionyour adt should provide for the conversion between floatingpoint values and fractions and the ability to produce string version of the fraction (bprovide python implementation of your fraction adt |
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 array structure for one-dimensional array and then use it to implement two-dimensional array and the related matrix structure the array structure at the hardware levelmost computer architectures provide mechanism for creating and using one-dimensional arrays one-dimensional array as illustrated in figure is composed of multiple sequential elements stored in contiguous bytes of memory and allows for random access to the individual elements the entire contents of an array are identified by single name individual elements within the array can be accessed directly by specifying an integer subscript or index valuewhich indicates an offset from the start of the array this is similar to the mathematics notation (xi )which allows for multiple variables of the same name the difference is that programming languages typically use square brackets following the array name to specify the subscriptx[ figure sample - array consisting of elements |
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 has limited number of operationswhich commonly include those for array creationreading value from specific elementand writing value to specific element the liston the other handprovides large number of operations for working with the contents of the list secondthe list can grow and shrink during execution as elements are added or removed while the size of an array cannot be changed after it has been created you may be wonderingif python provides the list structure as its mutable sequence typewhy are we bothering to discuss the array structuremuch less plan to implement an abstract data type for working with arrays in pythonthe short answer is that both structures have their uses there are many problems that only require the use of basic array in which the number of elements is known beforehand and the flexible set of operations available with the list is not needed the array is best suited for problems requiring sequence in which the maximum number of elements are known up frontwhereas the list is the better choice when the size of the sequence needs to change after it has been created as you will learn later in the list contains more storage space than is needed to store the items currently in the list this extra spacethe size of which can be up to twice the necessary capacityallows for quick and easy expansion as new items are added to the list but the extra space is wasteful when using list to store fixed number of elements for examplesuppose we need sequence structure with elements we could create list with the given number of elements using the replication operatorvalues none but underneaththis results in the allocation of space for up to , elementshalf of which will go to waste in this casean array would be better choice the decision as to whether an array or list should be used is not limited to the size of the sequence structure it also depends on how it will be used the list provides large set of operations for managing the items contained in the list some of these include inserting an item at specific locationsearching for an itemremoving an item by value or locationeasily extracting subset of itemsand sorting the items the array structureon the other handonly provides limited set of operations for accessing the individual elements comprising the array thusif the problem at hand requires these types of operationsthe list is the better choice the array abstract data type the array structure is commonly found in most programming languages as primitive typebut python only provides the list structure for creating mutable se |
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 elements are identified by unique integer subscript starting with zero once an array is createdits size cannot be changed arraysize )creates one-dimensional array consisting of size elements with each element initially set to none size must be greater than zero length ()returns the length or number of elements in the array getitem index )returns the value stored in the array at element position index the index argument must be within the valid range accessed using the subscript operator setitem indexvalue )modifies the contents of the array element at position index to contain value the index must be within the valid range accessed using the subscript operator clearingvalue )clears the array by setting every element to value iterator ()creates and returns an iterator that can be used to traverse the elements of the array some computer scientists consider the array physical structure and not an abstraction since arrays are implemented at the hardware level but rememberthere are only three basic operations available with the hardware-implemented array as part of our array adtwe have provided for these operations but have also included an iterator and operations for obtaining the size of the array and for setting every element to given value in this casewe have provided higher level of abstraction than that provided by the underlying hardware-implemented array the following simple program illustrates the creation and use of an array object based on the array adt comments are provided to highlight the use of the operator methods fill - array with random valuesthen print themone per line from array import array import random the constructor is called to create the array valuelist array |
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 the terminal we know that characters are represented by the ascii codewhich consists of integer values the letters of the alphabetboth upperand lowercaseare part of what' known as the printable range of the ascii code this includes the ascii values in the range [ along with some of the codes with smaller values the latter are known control characters and can include the tabnewlineand form-feed codes since all of the letters will have ascii values less than we can create an array of this size and let each element represent counter for the corresponding ascii value after processing the filewe can traverse over the elements used as counters for the letters of the alphabet and ignore the others the following program provides solution to this problem using the array adt#count the number of occurrences of each letter in text file from array import array create an array for the counters and initialize each element to thecounters array thecounters clear open the text file for reading and extract each line from the file and iterate over each character in the line thefile open'atextfile txt''rfor line in thefile for letter in line code ordletter thecounters[code+ close the file thefile close(print the results the uppercase letters have ascii values in the range and the lowercase letters are in the range for in range print"% % % % (chr( + )thecounters[ + ]chr( + )thecounters[ + ]implementing the array python is scripting language built using the languagea high-level language that requires program' source code be compiled into executable code before it can be used the language is very powerful programming language that provides |
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 appropriate types from the language while python does not provide the array structure as part of the language itselfit now includes the ctypes module as part of the python standard library this module provides access to the diverse set of data types available in the language and the complete functionality provided by wide range of libraries the ctypes module provides the capability to create hardware-supported arrays just like the ones used to implement python' stringlisttupleand dictionary collection types but the ctypes module is not meant for everyday use in python programs as it was designed for use by module developers to aide in creating more portable python modules by bridging the gap between python and the language much of the functionality provided by the ctypes module requires some knowledge of the language thusthe technique provided by the module for creating an array should not typically be used directly within python program but we can use it within our array class to provide the functionality defined by the array adt since the details will be hidden within the class creating hardware array the ctypes module provides technique for creating arrays that can store references to python objects the following code segment import ctypes arraytype ctypes py_object slots arraytype(creates an array named slots that contains five elements slots each of which can store reference to an object after the array has been createdthe elements can be accessed using the same integer subscript notation as used with python' own sequence types for the slots arraythe legal range is [ the elements of the array have to be initialized before they can be used if we attempt to read the contents of an element in the slots array before it has been initialized printslots[ |
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 choice is to assign none to each elementfor in range slots[inone the elements of the array can now be treated like any other variable in python that contains null referenceslots you may have noticed that we used the literal with the range(function to indicate the number of elements to be initialized this was necessary because hardware-supported array does not keep track of the array sizeit' up to the programmer to remember or maintain this value likewisethe programmer must also ensure they do not access an element outside the legal range references to any type of python object can be stored in any element of the array for examplethe following code segment stores three integers in various elements of the arrayslots[ slots[ slots[ the result of which is illustrated hereslots the operations provided by the array only allow for setting given element to given reference or accessing reference stored in given element to remove an item from the arraywe simply set the corresponding element to none for examplesuppose we want to remove value from the array slots[ none which results in the following change to the slots arrayslots |
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 with an arrayyou would have to provide the necessary code yourself the class definition the implementation of the array adt using hardware-supported array created with the use of the ctypes module is provided in listing listing the array py module with the array class implements the array adt using array capabilities of the ctypes module import ctypes class array creates an array with size elements def __init__selfsize )assert size "array size must be self _size size create the array structure using the ctypes module pyarraytype ctypes py_object size self _elements pyarraytype(initialize each element self clearnone returns the size of the array def __len__self )return self _size gets the contents of the index element def __getitem__selfindex )assert index > and index len(self)"array subscript out of rangereturn self _elementsindex puts the value in the array element at index position def __setitem__selfindexvalue )assert index > and index len(self)"array subscript out of rangeself _elementsindex value clears the array by setting each element to the given value def clearselfvalue )for in rangelen(selfself _elements[ivalue returns the array' iterator for traversing the elements def __iter__self )return _arrayiteratorself _elements an iterator for the array adt class _arrayiterator (listing continued |
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 initialization of the array using the technique described earlier it also defines two data fields needed for the implementation of the array adtone to store reference to the array structure and another to store the number of elements allocated for the array the latter is needed since hardware-supported arrays do not keep track of this value the initialization of the array is done by calling the clear(method the clear(method is used to set each element of the array to given valuewhich it does by iterating over the elements using an index variable the len methodwhich returns the number of elements in the arraysimply returns the value of size that was saved in the constructor the iter method creates and returns an instance of the arrayiterator private iterator classwhich is provided in lines - of listing the definition of the array adt calls for the implementation of the subscript operatorwhich allows for the use of array objects in manner similar to other python collection types in pythonas in most languagesthe subscript notation can be used to read the contents of an array element or to modify an element thusthere are two different methods that must be definedas shown in lines - firstthe getitem operator method takes the array index as an argument and returns the value of the corresponding element the precondition must first be verified to ensure the subscript is within the valid range when the subscript notation is used in programy [ ]python will call the getitem methodpassing the value of to the index parameter since python expects the getitem method to return valueit is your responsibility to make sure this occurs the setitem operator method is used to set or change the contents of specific element of the array it takes two argumentsthe array index of the element being modified and the new value that will be stored in that element before the element is modifiedthe precondition must be tested to verify the subscript is within the valid range python automatically calls the setitem method when the subscript notation is used to assign value to specific elementx[iy the indexispecified in the subscript is passed as the first argument and the value to be assigned is passed as the second argument__setitem__( , |
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 that is implemented using an array structure to store the items contained in the list in this sectionwe examine the implementation of python' listwhich can be very beneficial not only for learning more about abstract data types and their implementations but also to illustrate the major differences between an array and python' list structure we explore some of the more common list operations and describe how they are implemented using an array structure creating python list suppose we create list containing several valuespylist which results in the list(constructor being called to create list object and fill it with the given values when the list(constructor is calledan array structure is created to store the items contained in the list the array is initially created bigger than neededleaving capacity for future expansion the values stored in the list comprise subarray in which only contiguous subset of the array elements are actually used figure illustrates the abstract and physical views of our sample list in the physical viewthe elements of the array structure used to store the actual contents of the list are enclosed inside the dashed gray box the elements with null references shown outside the dashed gray box are the remaining elements of the underlying array structure that are still available for use this notation will be used throughout the section to illustrate the contents of the list and the underlying array used to implement it abstract view length physical view capacity array figure the abstract and physical views of list implemented using an array |
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 since that information is not part of the list definition appending items what happens when new item is appended to the end of list as in the following statementpylist append if there is room in the arraythe item is stored in the next available slot of the array and the length field is incremented by one the result of appending to pylist is illustrated in figure pylist figure result of appending value to the list what happens when the array becomes full and there are no free elements in which to add new list itemfor exampleconsider the following list operationspylist append pylist append pylist append after the second statement is executedthe array becomes full and there is no available space to add more values as illustrated in figure by definitiona list can contain any number of items and never becomes full thuswhen the third statement is executedthe array will have to be expanded to make room for value from the discussion in the previous sectionwe know an array cannot change size once it has been created to allow for the expansion of pylist figure full array resulting after appending three values |
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 appended to the end of the list in pythonthe amount by which the size of the array is increased is proportional to the current array size for illustration purposeswe assume an expansion creates new array that is double the size of the original the result of expanding the array and appending value to the list is shown in figure ( new arraydouble the size of the originalis created temparray ( the values from the original array are copied to the new larger array element-by-element copy ( the new array replaces the original in the list pylist ( value is appended to the end of the list pylist figure the steps required to expand the array to provide space for value |
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 capacity for all of the elementsthe underlying array has to be expanded as was done with the append(method since python knows how big the array needs to be in order to store all of the elements from both listsit only requires single expansion of the destination listpylista the new array will be created larger than needed to allow more items to be added to the list without first requiring an immediate expansion of the array after the new array is createdelements from the destination list are copied to the new array followed by the elements from the source listpylistbas illustrated in figure pylistb pylista pylista figure the result of extending pylista with pylistb inserting items an item can be inserted anywhere within the list using the insert(method in the following example pylist insert we insert the value at index position since there is already an item at that positionwe must make room for the new item by shifting all of the items down one position starting with the item at index position after shifting the itemsthe value is then inserted at position as illustrated in figure if there are no free slots for the new itemthe list will be expanded in the same fashion as described earlier |
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 list using the pop(method consider the following code segmentwhich removes both the first and last items from the sample listpylist pop pylist pop(remove the first item remove the last item the first statement removes the first item from the list after the item is removedtypically by setting the reference variable to nonethe items following it within the array are shifted downfrom left to rightto close the gap finallythe length of the list is decremented to reflect the smaller size figure on the next page illustrates the process of removing the first item from the sample list the second pop(operation in the example code removes the last item from the list since there are no items following the last onethe only operations required are to remove the item and decrement the size of the list after removing an item from the listthe size of the array may be reduced using technique similar to that for expansion this reduction occurs when the number of available slots in the internal array falls below certain threshold for examplewhen more than half of the array elements are emptythe size of the array may be cut in half list slice slicing is an operation that creates new list consisting of contiguous subset of elements from the original list the original list is not modified by this operation insteadreferences to the corresponding elements are copied and stored in 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 element index and the number of elements included in the subset consider the following example code segmentwhich creates slice from our sample listaslice thevector[ : to slice lista new list is created with capacity large enough to store the entire subset of elements plus additional space for future insertions the elements within the specified range are then copiedelement by elementto the new list the result of creating the sample slice is illustrated in figure pylist aslice figure the result of creating list slice |
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 view of both oneand two-dimensional array while computer architectures provide mechanism at the hardware level for creating and using one-dimensional arraysthey do not typically support arrays of higher dimensions insteadprogramming languages typically provide their own mechanism for creating and managing arrays that consist of multiple dimensions in this sectionwe explore two-dimensional arrays while arrays of higher dimensions are discussed later in the elements rows columns figure sample arrays(lefta - array viewed as sequential list and (righta - array viewed as rectangular table or grid the array abstract data type as we saw earlierpython does not directly support built-in arrays of any dimension butin the previous sectionwe were able to use the ctypes module to create one-dimensional hardware-supported array that we used to implement the array adt two-dimensional arrays are also very common in computer programmingwhere they are used to solve problems that require data to be organized into rows and columns since - arrays are not provided by pythonwe define the array abstract data type for creating - arrays it consists of limited set of operations similar to those provided by the one-dimensional array adt define array adt two-dimensional array consists of collection of elements organized into rows and columns individual elements are referenced by specifying the specific row and column indices (rc)both of which start at array dnrowsncols )creates two-dimensional array organized into rows and columns the nrows and ncols arguments indicate the size of the table the individual elements of the table are initialized to none numrows()returns the number of rows in the - array |
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 [ , setitemi value )modifies the contents of the - array element indicated by the -tuple ( with the new value both indices must be within the valid range accessed using the subscript operatorx[ , to illustrate the use of - arraysuppose we have collection of exam grades stored in text file for group of students that we need to process for examplewe may want to compute the average exam grade for each student or the average grade for each examor both sample text file is illustrated on the left in figure the file contains the grades for multiple studentseach of whom have grades for multiple exams the first line indicates the number of students for whom we have gradesand the second line indicates the number of exams for which each student has grade the remaining lines contain the actual exam grades each line contains the grade for an individual studentwith the grades listed in exam order since we have multiple grades for multiple studentswe can store the grades in - array in which each row contains the grades for an individual student and each column contains the grades for given exam - array used to store the exam grades from the sample file is illustrated on the right in figure figure exam grades(leftstored in text fileand (rightstored in - array the following code segment shows the implementation needed to extract the exam grades from the text file and store them into - array notice that we create the array after extracting the first two values from the file these values indicate the number of students and the number of exams that correspond to the number of rows and columns needed in the array |
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 remaining lines for student in gradefile grades student split(for in rangenumexams )examgrades[ ,jintgrades[ji + close the text file gradefile close(with the grades extracted from the file and stored in the - arraywe can now process the grades as needed suppose we want to compute and display each student' exam gradewhich we can do with the following codecompute each student' average exam grade for in rangenumstudents tally the exam grades for the ith student total for in rangenumexams total +examgrades[ ,jcompute average for the ith student examavg total numexams print"% % ( + examavgimplementing the - array we now turn our attention to the implementation of the - array there are several approaches that we can use to store and organize the data for - array two of the more common approaches include the use of single - array to physically store the elements of the - array by arranging them in order based on either row or columnwhereas the other uses an array of arrays we are going to use the latter approach to implement the array abstract data type and delay discussion of the former approach until later in the when using an array of arrays to store the elements of - arraywe store each row of the - array within its own - array thenanother - array is used to store references to each of the arrays used to store the row elements figure shows the abstract view of - array and the physical storage of that - array using an array of arrays |
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 access to the given - arraythese languages use the subscript notation [ ][cfor referencing an individual element to be consistent in our approach of hiding the implementation detailswe do not provide access to any of the - arrays used to store the elements of the - array thusour implementation requires the use of the subscript notation [ ,cthe implementation of the array abstract data type using an array of arrays is provided in listing the constructor creates data field named therows to which an array object is assigned this is the main array used to store the references to the other arrays that are created for each row in the - array listing the array py module with the array class implementation of the array adt using an array of arrays class array creates - array of size numrows numcols def __init__selfnumrowsnumcols )create - array to store an array reference for each row self _therows arraynumrows create the - arrays for each row of the - array for in rangenumrows self _therows[iarraynumcols returns the number of rows in the - array def numrowsself )return lenself _therows returns the number of columns in the - array def numcolsself )return lenself _therows[ clears the array by setting every element to the given value def clearselfvalue )for row in rangeself numrows()row clearvalue |
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 contents of the element at position [ ,jto value def __setitem__selfndxtuplevalue )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[rowthe darray[colvalue basic operations note that the size of the array that is passed as arguments to the constructor is not saved in data fields the numrows(method can obtain the number of rows by checking the length of the main arraywhich contains an element for each row in the - array to determine the number of columns in the - arraythe numcols(method can simply check the length of any of the - arrays used to store the individual rows the clear(method can set every element to the given value by calling the clear(method on each of the - arrays used to store the individual rows this is easily done by iterating over the array stored in therows element access access to individual elements within an - array requires -tuple or twocomponent subscriptone for each dimension in mathematicsthe -tuple subscript is generally notated as xr, in modern programming languagesa -tuple subscript is given either as [ ][cor [ ,cin pythonwe can use the latter notation in conjunction with the getitem and setitem subscript operators this will allow for more natural use of the two-dimensional array instead of having to invoke named method the python subscript operator method getitem which is shown in lines - takes single index argument as specified in the method definition this does not restrict the subscript to single index valuehowever when multicomponent subscript is specified ( [ , ])python automatically stores |
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 reference to the array used to store the given row with this reference stored in the local variable the darraywe can then apply the subscript operator to the - array using the column value you may notice second assert statement within the getitem method at line this is needed because python does not examine the number of components specified in the subscript before passing the tuple to the subscript operator method for examplethere is nothing to prevent us from incorrectly supplying three components such as box[ , ,kinstead of two in factpython would have no way of knowing that we only need two components for the - array subscript thuswe must first check to make sure the subscript tuple passed to the method contains only two elements when making the assertion about the size of the ndxtuplewe assume tuple is passed to the subscript operator and use the len(function to verify its length when single-component subscript [ is supplied to subscript operator methodas is done with the array classthe argument is single integer value the len(method can only be used with the collection types and not individual values it does generate its own errorhoweverwhen used improperly thuspython' len(function is used to ensure two components are supplied for all array objects the setitem operator method can be implemented in similar fashion to getitem the major differences are that this method requires second argument to receive the value to which an element is set and it modifies the indicated element with the new value instead of returning value the matrix abstract data type in mathematicsa matrix is an rectangular grid or table of numerical values divided into rows and columns matriceswhich are an important tool in areas such as linear algebra and computer graphicsare used in number of applicationsincluding representing and solving systems of linear equations the matrix adt is defined next define matrix adt matrix is collection of scalar values arranged in rows and columns as rectangular grid of fixed size the elements of the matrix can be accessed by specifying given row and column index with indices starting at matrixrowsncols )creates new matrix containing nrows and ncols with each element initialized to numrows()returns the number of rows in the matrix |
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 )multiplies each element of the matrix by the given scalar value the matrix is modified by this operation transpose()returns new matrix that is the transpose of this matrix add rhsmatrix )creates and returns new matrix that is the result of adding this matrix to the given rhsmatrix the size of the two matrices must be the same subtract rhsmatrix )the same as the add(operation but subtracts the two matrices multiply rhsmatrix )creates and returns new matrix that is the result of multiplying this matrix to the given rhsmatrix the two matrices must be of appropriate sizes as defined for matrix multiplication matrix operations number of operations can be performed on matrices we first describe some of the more common ones and provide examples as review of matrix arithmetic addition and subtraction two matrices can be added or subtracted to create third matrix when adding two matricescorresponding elements are summed as illustrated here subtraction is performed in similar fashion but the corresponding elements are subtracted instead of summed + + + + + scaling matrix can be uniformly scaledwhich modifies each element of the matrix by the same scale factor scale factor of less than has the effect of reducing the value of each element whereas scale factor greater than increases the value of each element scaling matrix by scale factor of is illustrated here * * * * * |
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 of columns as the matrix on the righthand side in other wordsgiven matrix of size multiplied by matrix of size pthe resulting matrix is of size in multiplying two matriceseach element of the new matrix is the result of summing the product of row in the lefthand side matrix by column in the righthand side matrix in the example matrix multiplication illustrated herethe row and column used to compute entry ( of the new matrix is shaded in gray ( ( ( ( ( ( ( ( ( viewing matrix multiplication based on the element subscripts can help you to better understand the operation consider the two matrices from above and assume they are labeled and brespectively , , , , , , bb , , , , , , the computation of the individual elements resulting from multiplying and ( bis performed as followsc , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , |
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 there are number of ways to organize the data for the matrix adtbut the most obvious is with the use of two-dimensional array or rectangular grid having defined and implemented the array adtwe can utilize it to implement the matrix adt as shown in listing listing the matrix py module implementation of the matrix adt using - array from array import array class matrix creates matrix of size numrows numcols initialized to def __init__selfnumrowsnumcols )self _thegrid array dnumrowsnumcols self _thegrid clear returns the number of rows in the matrix def numrowsself )return self _thegrid numrows(returns the number of columns in the matrix def numcolsself )return self _thegrid numcols(returns the value of element (ij) [ ,jdef __getitem__selfndxtuple )return self _thegridndxtuple[ ]ndxtuple[ sets the value of element ( ,jto the value sx[ ,js def __setitem__selfndxtuplescalar )self _thegridndxtuple[ ]ndxtuple[ scalar (listing continued |
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__selfrhsmatrix )assert rhsmatrix numrows(=self numrows(and rhsmatrix numcols(=self numcols()"matrix sizes not compatible for the add operation create the new matrix newmatrix matrixself numrows()self numcols(add the corresponding elements in the two matrices for in rangeself numrows(for in rangeself numcols(newmatrixrc selfrc rhsmatrixrc return newmatrix creates and returns new matrix that results from matrix subtraction def __sub__selfrhsmatrix )creates and returns new matrix resulting from matrix multiplication def __mul__selfrhsmatrix ) matrix object only requires one data field for storing the - array after creating the arrayits elements must be set to zero as specified by the definition of the matrix adt the constructor is provided in lines - the numrows(and numcols(methods are straightforward they need only return the length of the corresponding dimension of the - array the element access methods are also rather simple as they need only call the corresponding method from the array class note that we do not check for valid indices in these methods even though it is precondition as defined by the matrix adt the validation of the precondition is omitted here since we know the corresponding methods of the array class have the same preconditions and they are verified by that class if this were not the casewe would have to validate the indices and raise an exception directly within the methods of the matrix class the scaling matrix operationshown in lines - involves multiplying each element in the matrix by the given scalar value the matrix adt calls for this operation to modify the matrix on which it is applied instead of creating new matrix resulting from the multiplication the matrix add operationon the other handcreates and returns new matrix object that is the result of adding the |
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 operation is then returned the implementation of the remaining methodswhich is left as an exercisecan be done in similar fashion applicationthe game of life the game of lifedevised by british mathematician john conwayis solitairetype game that is analogous with "the risefall and alternations of society of living organisms the gamewhich is actually zero-player gamewas first introduced by martin gardner in his mathematical games column in the october issue of scientific american since its introductionlife has attracted much attention and has been widely studied as it can be used to observe how complex systems or patterns can evolve from simple set of rules the game of life was an early example of problem in the modern field of mathematics called cellular automata rules of the game the game uses an infinite-sized rectangular grid of cells in which each cell is either empty or occupied by an organism the occupied cells are said to be alivewhereas the empty ones are dead the game is played over specific period of time with each turn creating new "generationbased on the arrangement of live organisms in the current configuration the status of cell in the next generation is determined by applying the following four basic rules to each cell in the current configuration if cell is alive and has either two or three live neighborsthe cell remains alive in the next generation the neighbors are the eight cells immediately surrounding cellverticallyhorizontallyand diagonally living cell that has no live neighbors or single live neighbor dies from isolation in the next generation living cell that has four or more live neighbors dies from overpopulation in the next generation dead cell with exactly three live neighbors results in birth and becomes alive in the next generation all other dead cells remain dead in the next generation |
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 of lifeconsider the following simple configuration of live organismsapplying the rules to this configuration creates the next generation this results in two organisms dying (shown below as the light gray boxesbased on rule one remaining alive based on rule and the generation of new organism based on rule (the black box marked with an xx if we evolve the next generationthe system dies out since both live cells in the first generation have single live neighbor while some systems may eventually die outothers can evolve into "stablestate consider the following initial configuration and its first generation the result is stable state since the four live cells each have three neighbors and no dead cell has exactly three neighbors in order to produce new live cell another interesting patterns is the "two-phase oscillator,which alternates between successive generationsinitial configuration st generation nd generation |
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 area in the game of life that contains organisms the grid contains rectangular grouping of cells of finite size divided into rows and columns the individual cellswhich can be alive or deadare referenced by row and column indicesboth of which start at zero lifegridnrowsncols )creates new game grid consisting of nrows and ncols all cells in the grid are set to dead numrows()returns the number rows in the grid numcols()returns the number of columns in the grid configurecoordlist )configures the grid for evolving the next 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 we now develop program for the game of life using the life grid adt the implementation of the program provided in listing on the next page was developed using top-down design consisting of several functions the main routine creates the game grid and evolves new generations of organisms it relies on two additional functionsdraw(and evolve(the draw(routinethe implementation of which is left as an exerciseprints text-based representation of the game grid the evolve(function generates |
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 configure it grid lifegridgrid_widthgrid_height grid configureinit_config play the game drawgrid for in rangenum_gens )evolvegrid drawgrid generates the next generation of organisms def evolvegrid )list for storing the live cells of the next generation livecells list(iterate over the elements of the grid for in rangegrid numrows(for in rangegrid numcols(determine the number of live neighbors for this cell neighbors grid numliveneighborsij add the ( ,jtuple to livecells if this cell contains live organism in the next generation if (neighbors = and grid islivecellij )or (neighbors = livecells append(ijreconfigure the grid using the livecells coord list grid configurelivecells prints text-based representation of the game grid def drawgrid )executes the main routine main( |
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 cannot be modified with the next generation until the neighbor count has been computed for each cell in the current generation the program also defines several constant variables these are used to specify the grid sizethe number of generations to be createdand the set of initial live cells using constant variables allows for easy modifications to any of these parameters as needed without having to modify other parts of the program of coursethis information could be extracted from the user or text file instead the results of executing the gameoflife py program are illustrated graphically in figure initial configuration st generation nd generation rd generation th generation th generation th generation th generation th generation figure the results of using the gameoflife py program on sample grid configuration configurations after the eighth generation produce two-phase oscillatoralternating between the configuration of the seventh and eighth generations implementation the actual game of life specifies rectangular grid of infinite size when developing computer solution for such problemwe are limited to grids of fixed size the game of life can still be implementedhoweverby using finite size for the grid if the system grows too large where it does not fit into the spaceit can be "playedagainwith larger grid before implementing the lifegrid classwe must decide how the data should be organized and select an appropriate structure the most obvious is the use of two-dimensional array to represent the grid nextwe must decide what values to store in the grid to represent the organismsboth dead and alive any pair of values can be used we are going to use the value to represent the dead cells and the |
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 the game grid the lifegrid class is implemented in listing at the top of the class definitionbefore specifying the constructortwo constant variables are initialized to store the values used to mark the cells within the game grid these constants are defined within the class itself and outside of the methods since they are not actual data fields of lifegrid object by using the named constantsthe code is easier to read and the values used to represent the cell status could easily be changed if we were so inclined the constructorshown in lines - creates - array for the grid using the array class defined earlier in the the cells are cleared as the adt definition requires by calling the configure(method with an empty coordinate list the grid dimension accessor methods are easily implemented using the corresponding methods of the array class the three cell modification routines are also straightforward note that the adt definition requires the cell indices specified for the clearcell(and setcell(methods must be valid since this is also the precondition required of the array element access methodswe omit the direct specification of assertions in these methods the configure(methodshown in lines - clears the grid cells by setting each to dead organism it then iterates through the coordinate list and uses the setcell(method to set the live cells the numliveneighbors(method is left as an exercise notehoweversince we used the integer values and to represent the state of cellcounting the number of live neighbors is as simple as summing the contents of the neighboring cells working with fixed-size grid introduces the problem of how to deal with the cells around the border border cell will not have all eight neighbors since some of them lie outside the grid different approaches can be taken when border cell note constant variables constant variables defined within class are actually class variables that are unique to the class and not to individual objects to reference class constant variableuse the name of the class in place of the self keyword ( printgamegrid dead celli |
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 and initializes the cells to dead def __init__selfnumrowsnumcols )allocate the - array for the grid self _grid array dnumrowsnumcols clear the grid and set all cells to dead self configurelist(returns the number of rows in the grid def numrowsself )return self _grid numrows(returns the number of columns in the grid def numcolsself )return self _grid numcols(configures the grid to contain the given live cells def configureselfcoordlist )clear the game grid for in rangenumrows )for in rangenumcols )self clearcellij set the indicated cells to be alive for coord in coordlist self setcellcoord[ ]coord[ does the indicated cell contain live organismdef islivecellselfrowcol )return self _grid[rowcol=gamegrid live_cell clears the indicated cell by setting it to dead def clearcellselfrowcol )self _grid[rowcolgamegrid dead_cell sets the indicated cell to be alive def setcellselfrowcol )self _grid[rowcolgamegrid live_cell returns the number of live neighbors for the given cell def numliveneighborsselfrowcol ) |
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 are indicated using period and live cells are indicated using the symbol modify the gameoflife py program to prompt the user for the grid size and the number of generations to evolve use your program from exercise to experiment with the initial configurations shown in figure answer the following questions for each configuration using variety of grid sizes and assuming no more than generations (adoes the configuration die out(bdoes the configuration become stable(cdoes the configuration become an oscillator(dhow many generations were required before each configuration resulted in one of the states indicated in parts ( ( )figure sample game of life configurations |
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 types consider the implementation of the array abstract data type as described in the if we had used list of lists to implement the adtinstead of the array of arraysa large amount of extra storage space would be allocated that would never be used calculate the number of elements that will be allocated when using an array of arrays implementation and list of lists implementation of the array abstract data type for each of the following - array sizes( ( ( programming projects while python provides the built-in list type for constructing and managing mutable sequencesmany languages do not provide such structureat least not as part of the language itself to help in further understanding how python' built-in list worksimplement the vector adt using the array class implemented in the your implementation should produce mutable sequence type that works like python' list structure when the underlying array needs to be expandedthe new array should double the size of the original the operations that can be performed on the adt are described below assume the size of the underlying array never decreases vector()creates new empty vector with an initial capacity of two elements length ()returns the number of items contained in the vector contains item )determines if the given item is contained in the vector getitem ndx )returns the item stored in the ndx element of the list the value of ndx must be within the valid range setitem ndxitem )sets the element at position ndx to contain the given item the value of ndx must be within the valid rangewhich includes the first position past the last item appenditem )adds the given item to the end of the list insertndxitem )inserts the given item in the element at position ndx the items in the elements at and following the given position are shifted down to make room for the new item ndx must be within the valid range removendx )removes and returns the item from the element from the given ndx position the items in the elements at and following the given position are shifted up to close the gap created by the removed item ndx must be within the valid range |
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 vector between and including those indicated by the given from and to positions both the from and to positions must be within the valid range iterator ()creates and returns an iterator that can be used to traverse the elements of the vector in typical vector adtthe size of the underlying array decreases after sufficient number of items have been removed devise strategy for decreasing the size of the array as items are removed modify your implementation of the vector adt from the previous question to include your reduction strategy grayscale digital image is two-dimensional raster image in which the picture elementsor pixelsstore single value representing shade of gray that varies from black to white in discrete grayscale imagethe shades of gray are represented by integer values in the range [ ]where is black and is white we can define the grayscale image adt for storing and manipulating discrete grayscale digital images given the description of the operationsprovide complete implementation of the adt using - array grayscaleimagenrowsncols )creates new instance that consists of nrows and ncols of pixels each set to an initial value of width()returns the width of the image height()returns the height of the image clearvalue )clears the entire image by setting each pixel to the given intensity value the intensity value will be clamped to or if it is less than or greater than respectively getitem rowcol )returns the intensity level of the given pixel the pixel coordinates must be within the valid range setitem rowcolvalue )sets the intensity level of the given pixel to the given value the pixel coordinates must be within the valid range the intensity value is clamped to or if it is outside the valid range playing board games on computer is very common we can use abstraction to aide in the design of board game by separating the game logic from the actual user interaction required to play the game no matter the type of user interface provided to play the game ( text baseddesktop windowing environmentor web browser)the underlying logic remains the same consider the game of reversiwhich was invented in but has more modern set of rules dating back to the reversi is played by two players on game |
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 their color on the board at the end of the game the game starts with configuration as shown in part (aof figure (ax ( (cx ( (efigure moves in the game of reversi the players take turns placing chips on the board with their color facing up chip can only be played in square that is adjacent to chip of the other player and that forms straight line of attack (verticalhorizontalor diagonala line of attack is formed between two squares containing the player' own chips in which there is one or more of the opponent' chips in between the two for exampleif player (blackgoes firsthe has four options as shown in part (bsuppose player places chip in the square marked with an after placing his chipplayer flips all of the chips of player (whitethat are in the line of attack in this casehe flips the chip immediately below the new chip as shown in part (cplayer then places one of her chips she has three options from which to choose as shown by the dark squares in part (cif player places her chip in the square marked xshe flips the black chip below the new chip as shown in part (dif there are multiple lines of attack that result from the placement of chipthen all of the opponent' chips that are in all of the lines of attack are flipped for examplesuppose player places chip in the square marked with an as shown in part (dthen he flips both white chipsthe one to the left and the one diagonally down to the left as shown in part (eplay alternates between the players until all of the squares are filled or neither player can move if one player cannot move but the other canplay proceeds with the other player the winner is the player with the most chips at the end of the game given the following description of the operationsprovide complete implementation for the reversi game logic adt reversigamelogic()creates new instance of the reversi game logic with the initial configuration whoseturn()returns the player number ( or for the current player or if no player can move |
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 islegalmoverowcol )returns true or false to indicate if the current player can place their chip in the square at position (rowcoloccupiedbyrowcol )which player has chip in the given squarereturns the player number ( or or if the square is empty makemoverowcol )the current player places one of his chips in the square at position (rowcolall chips on the board that should be flipped based on the rules of reversi are flipped implement text-based version of the reversi game using your game logic adt from the previous question define game logic adtsimilar to that of the reversi game logic adtfor the game of checkers |
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 neverthelessit' still important to understand how they work and some of the common ways in which they are implemented your experience in programming will likely not be limited to the python language at some point in the futureyou may use one if not several other common programming languages while some of these do provide wide range of abstract data types as part of the language itself or included in their standard libraryotherslike cdo not thusit' important that you know how to implement set or dictionary adt if necessarywhen one is not available as part of the language furtherboth the set and dictionary types provide excellent examples of abstract data types that can be implemented using different data structures as you learned in there may be multiple data structures and ways to organize the data in those structures that are suitable for implementing an abstract data type thusit' not uncommon for language libraries to provide multiple implementations of an abstract data typewhich allows the programmer to choose the best option for given problem your ability to choose from among these various implementations will depend not only on your knowledge of the abstract data type itselfbut also on understanding the pros and cons of the various implementations sets the set adt is common container used in computer science but unlike the bag adt introduced in set stores unique values and represents the same structure found in mathematics it is commonly used when you need to store collection of unique values without regard to how they are stored or when you need to perform various mathematical set operations on collections |
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 domain in which the stored values have no particular ordering set()creates new set initialized to the empty set length ()returns the number of elements in the setalso known as the cardinality accessed using the len(function contains element )determines if the given value is an element of the set and returns the appropriate boolean value accessed using the in operator addelement )modifies the set by adding the given value or element to the set if the element is not already member if the element is not uniqueno action is taken and the operation is skipped removeelement )removes the given value from the set if the value is contained in the set and raises an exception otherwise equals setb )determines if the set is equal to another set and returns boolean value for two setsa and bto be equalboth and must contain the same number of elements and all elements in must also be elements in if both sets are emptythe sets are equal access with =or !issubsetofsetb )determines if the set is subset of another set and returns boolean value for set to be subset of ball elements in must also be elements in unionsetb )creates and returns new set that is the union of this set and setb the new set created from the union of two setsa and bcontains all elements in plus those elements in that are not in neither set nor set is modified by this operation intersectsetb )creates and returns new set that is the intersection of this set and setb the intersection of sets and contains only those elements that are in both and neither set nor set is modified by this operation differencesetb )creates and returns new set that is the difference of this set and setb the set differencea bcontains only those elements that are in but not in neither set nor set is modified by this operation |
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 illustrated in figure smith set(smith add"csci- smith add"math- smith add"hist- smith add"econ- roberts set(roberts add"pol- roberts add"anth- roberts add"csci- roberts add"econ- smith set "csci- "math- "econ- "hist- roberts set "csci- "pol- "econ- "anth- figure abstract view of the two sample sets nextwe determine if the two students are taking the exact same courses if notthen we want to know if they are taking any of the same courses we can do this by computing the intersection between the two sets if smith =roberts print"smith and roberts are taking the same courses else samecourses smith intersectionroberts if samecourses isempty(print"smith and roberts are not taking any of ""the same courses else print"smith and roberts are taking some of the ""same courses:for course in samecourses printcourse |
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 difference operationuniquecourses smith differenceroberts for course in samecourses printcourse this example reinforces one of the advantages of working with an abstraction by focusing on what functionality the adt provides instead of how that functionality is implemented by hiding the implementation detailswe can use an adt independent of its implementation in factthe choice of implementation for the set adt will have no effect on the instructions in our example program selecting data structure to implement the set adtwe must select data structure based on the same criteria we used for the bag adt from since we are trying to replicate the functionality of the set structure provided by pythonwe don' want to use that structure that leaves the arraylistand dictionary containers for consideration in implementing the set adt the storage requirements for the bag and set are very similar with the difference being that set cannot contain duplicates the dictionary would seem to be the ideal choice since it can store unique itemsbut it would waste space in this case rememberthe dictionary stores key/value pairswhich requires two data fields per entry we could store the individual items of the set in the key fields and leave the value fields emptybut that would use twice the amount of storage than necessary this waste does not occur with an array or list an array could be used to implement the setbut set can contain any number of elements and by definition an array has fixed size to use the array structurewe would have to manage the expansion of the array when necessary in the same fashion as it' done for the list since the list can grow as neededit seems ideal for storing the elements of set just as it was for the bag and it does provide for the complete functionality of the adt since the list allows for duplicate valueshoweverwe must make sure as part of the implementation that no duplicates are added to our set list-based implementation having selected the list structurewe can now implement the set adt as shown in listing some of the operations of the set are very similar to those of the bag adt and are implemented in similar fashion sample instances for the two sets from figure are illustrated in figure |
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 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 )return element in self _theelements adds new unique element to the set def addselfelement )if element not in self self _theelements appendelement removes an element from the set def removeselfelement )assert element in self"the element must be in the set self _theelements removeitem determines if two sets are equal def __eq__selfsetb )if lenself !lensetb return false else return self issubsetofsetb (listing continued |
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 element not in self newset _theelements appendelement return newset creates new set from the intersectionself set and setb def intersetselfsetb )creates new set from the differenceself set and setb def differenceselfsetb )returns an iterator for traversing the list of items def __iter__self )return _setiteratorself _theelements adding elements as indicated earlierwe must ensure that duplicate values are not added to the set since the list structure does not handle this for us when implementing the add methodshown in lines - we must first determine if the supplied element is already in the list or not if the element is not duplicatewe can simply append the value to the end of the listif the element is duplicatewe do nothing the reason for this is that the definition of the add(operation indicates no action is taken when an attempt is made to add duplicate value this is known as noopwhich is short for no operation and indicates no action is taken noops are appropriate in some caseswhich will be stated implicitly in the definition of an abstract data type by indicating no action is to be taken when the precondition fails as we did with the add(operation comparing two sets for the operations that require second set as an argumentwe can use the operations of the set adt itself to access and manipulate the data of the second set consider the "equalsoperationimplemented in lines - of listing which determines if both sets contain the exact same elements we first check to make |
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 would be inefficient to compare the individual elements since we already know the two sets cannot be equal after verifying the size of the listswe can test to see if the self set is subset of setb by calling self issubsetof(setbthis is valid test since two equal sets are subsets of each other and we already know they are of the same size to determine if one set is the subset of anotherwe can iterate over the list of elements in the self set and make sure each is contained in setb if just one element in the self set is not in setbthen it is not subset the implementation of the issubsetof(method is shown in lines - the set union some of the operations create and return new set based on the originalbut the original is not modified this is accomplished by creating new set and populating it with the appropriate data from the other sets consider the union(methodshown in lines - which creates new set from the self set and setb passed as an argument to the method creating new setpopulated with the unique elements of the other two setsrequires three steps( create new set( fill the newset with the elements from setband ( iterate through the elements of the self setduring which each element is added to the newset if that element is not in setb for the first stepwe simply create new instance of the set class the second step is accomplished with the use of the list extend(method it directly copies the entire contents of the list used to store the elements of the self set to the list used to store the elements of the newset for the final stepwe iterate through the elements of setb and add those elements to the the newset that are not in the self set the unique elements are added to the newset by appending them to the list used to store the elements of the newset the remaining operations of the set adt can be implemented in similar fashion and are left as exercises maps searching for data items based on unique key values is very common application in computer science an abstract data type that provides this type of search capability is often referred to as map or dictionary since it maps key to corresponding value consider the problem of university registrar having to manage and process large volumes of data related to students to keep track of the information or records of datathe registrar assigns unique student identification |
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 multiple students have the same nameorwhat happens if the name was entered incorrectly when the record was initially created brown john east main st smith somewhere john va east main st roberts somewhere john va east main st smith somewhere john va east main st somewhere va figure unique key/data pairs in this sectionwe define our own map adt and then provide an implementation using list in later we will implement and evaluate the map using variety of data structures we use the term map to distinguish our adt from the dictionary provided by python the python dictionary is implemented using hash tablewhich requires the key objects to contain the hash method for generating hash code this can limit the type of problems with which dictionary can be used we define our map adt with the minimum requirement that the keys are comparablewhich will allow it to be used in wider range of problems it' not uncommon to provide multiple implementations of an adt as is done with many language libraries we will explore the implementation details of python' dictionary later in when we discuss hash tables and the design of hash functions the map abstract data type the map adt provides great example of an adt that can be implemented using one of many different data structures our definition of the map adtwhich is provided nextincludes the minimum set of operations necessary for using and managing map |
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 the key is found and false otherwise addkeyvalue )adds new key/value pair to the map if the key is not already in the map or replaces the data associated with the key if the key is in the map returns true if this is new key and false if the data associated with the existing key is replaced removekey )removes the key/value pair for the given key if it is in the map and raises an exception otherwise valueofkey )returns the data record associated with the given key the key must exist in the map or an exception is raised iterator ()creates and returns an iterator that can be used to iterate over the keys in the map list-based implementation we indicated earlier that many different data structures can be used to implement map since we are trying to replicate the functionality of the dictionary provided by pythonwe don' want to use that structure that leaves the use of an array or list as with the set adtboth the array and list structures can be usedbut the list is better choice since it does not have fixed size like an array and it can expand automatically as needed in the implementation of the bag and set adtswe used single list to store the individual elements for the map adthoweverwe must store both key component and the corresponding value component for each entry in the map we cannot simply add the component pairs to the list without some means of maintaining their association one approach is to use two listsone for the keys and one for the corresponding values accessing and manipulating the components is very similar to that used with the bag and set adts the differencehoweveris that the association between the component pairs must always be maintained as new entries are added and existing ones removed to accomplish thiseach key/value must be stored in corresponding elements of the parallel lists and that association must be maintained |
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 figure entrylist map mapentry smith smith john john east east main main st st somewhere somewhere va va smith smith jane jane jefferson jefferson st st east east end end pa pa roberts roberts susan susan quarry quarry rd rd nowhere nowhere tx tx brown brown jessica jessica quarry quarry rd rd plains plains tn tn figure the map adt implemented using single list the implementation of the map adt using single list is provided in listing as we indicated earlier in we want to avoid the use of tuples when storing structured data since it' better practice to use classes with named fields the mapentry storage classdefined in lines - will be used to store the individual key/value pairs note this storage class is defined to be private since it' only intended for use by the map class that provides the single list implementation of the map adt listing the linearmap py module implementation of map adt using single list class map creates an empty map instance def __init__self )self _entrylist list(returns the number of entries in the map def __len__self )return lenself _entrylist determines if the map contains the given key def __contains__selfkey )ndx self _findpositionkey return ndx is not none adds new entry to the map if the key does exist otherwisethe |
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 the key def valueofselfkey )ndx self _findpositionkey assert ndx is not none"invalid map key return self _entrylist[ndxvalue removes the entry associated with the key def removeselfkey )ndx self _findpositionkey assert ndx is not none"invalid map key self _entrylist popndx returns an iterator for traversing the keys in the map def __iter__self )return _mapiteratorself _entrylist helper method used to find the index position of category if the key is not foundnone is returned def _findpositionselfkey )iterate through each entry in the list for in rangelen(selfis the key stored in the ith entryif self _entrylist[ikey =key return when not foundreturn none return none storage class for holding the key/value pairs class _mapentry def __init__selfkeyvalue )self key key self value value many of the methods require search to determine if the map contains given key in this implementationthe standard in operator cannot be used since the list contains mapentry objects and not simply key entries insteadwe have to search the list ourselves and examine the key field of each mapentry object likewisewe routinely have to locate within the list the position containing specific key/value entry since these operations will be needed in several methodswe can create helper method that combines the two searches and use it where needed the findposition(helper method searches the list for the given key if the key is foundthe index of its location is returnedotherwisethe function |
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 need to first determine if the map contains the key and then searching again for its location given the helper methodthe implementation of the various methods is straightforward implementation of the iterator method is left as an exercise multi-dimensional arrays in we worked with oneand two-dimensional arraysbut arrays can be larger than two dimensions in factarrays can contain any number of dimensions that may be needed for given problem multi-dimensional array stores collection of data in which the individual elements are accessed with multicomponent subscriptsxi, or yi, , figure illustrates the abstract view of twoand three-dimensional array as we saw earliera two-dimensional array is typically viewed as table or grid consisting of rows and columns an individual element is accessed by specifying two indicesone for the row and one for the column the three-dimensional array can be visualized as box of tables where each table is divided into rows and columns individual elements are accessed by specifying the index of the table followed by the row and column indices larger dimensions are used in the solutions for some problemsbut they are more difficult to visualize columns les tab rows rows columns figure sample multi-dimensional arrays(lefta - array viewed as rectangular table and (righta - array viewed as box of tables most high-level programming languages provide convenient way to create and manage multi-dimensional arrays while others require more hands-on approach +and java are two examples of languages that provide multi-dimensional arrays as part of the language pythonof coursedoes not directly support arrays of any dimension but that did not prevent us from defining and implementing abstract data types in the previous for oneand two-dimensional arrays likewisewe can define an abstract data type for creating and using arrays of any dimension |
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 adt multi-dimensional array consists of collection of elements organized into multiple dimensions individual elements are referenced by specifying an -tuple or subscript of multiple components( in )one for each dimension of the array all indices of the -tuple start at zero multiarrayd dn )creates multi-dimensional array of elements organized into -dimensions with each element initially set to none the number of dimensionswhich is specified by the number of argumentsmust be greater than the individual argumentsall of which must be greater than zeroindicate the lengths of the corresponding array dimensions the dimensions are specified from highest to lowestwhere is the highest possible dimension and dn is the lowest dims()returns the number of dimensions in the multi-dimensional array lengthdim )returns the length of the given array dimension the individual dimensions are numbered starting from where represents the firstor highestdimension possible in the array thusin an array with three dimensions indicates the number of tables in the box is the number of rowsand is the number of columns clearvalue )clears the array by setting each element to the given value getitem in )returns the value stored in the array at the element position indicated by the -tuple ( in all of the specified indices must be given and they must be within the valid range of the corresponding array dimensions accessed using the element operatory setitem in value )modifies the contents of the specified array element to contain the given value the element is specified by the -tuple ( in all of the subscript components must be given and they must be within the valid range of the corresponding array dimensions accessed using the element operatorx data organization most computer architectures provide mechanism at the hardware level for creating and using one-dimensional arrays programming languages need only provide |
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 elements stored in successive memory locations the index used to reference particular element is simply the offset from the first element in the array in most programming languagesa multi-dimensional array is actually created and stored in memory as one-dimensional array with this organizationa multi-dimensional array is simply an abstract view of physical one-dimensional data structure array storage one-dimensional array is commonly used to physically store arrays of higher dimensions consider two-dimensional array divided into table of rows and columns as illustrated in figure how can the individual elements of the table be stored in the one-dimensional structure while maintaining direct access to the individual table elementsthere are two common approaches the elements can be stored in row-major order or column-major order most high-level programming languages use row-major orderwith fortran being one of the few languages that uses column-major ordering to store and manage - arrays figure the abstract view of sample two-dimensional array in row-major orderthe individual rows are stored sequentiallyone at timeas illustrated in figure the first row of elements are stored in the first sequential elements of the - arraythe second row of elements are stored in the next five sequential elementsand so forth in column-major orderthe - array is stored sequentiallyone entire column at timeas illustrated in figure the first column of elements are stored in the first sequential elements of the - arrayfollowed by the elements of the second columnand so on for larger dimensionsa similar approach can be used with three-dimensional arraythe individual tables can be stored contiguously using either row-major or column-major ordering as the number of dimensions growall elements within single instance of each dimension are stored contiguously before the next instance for examplegiven four-dimensional arraywhich can be thought of as an array of boxesall elements of an individual box ( - arrayare stored before the next box |
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 the language when an individual element of - array is accessedthe compiler must include additional instructions to calculate the offset of the specific element within the - array given - array of size mxn and using row-major orderingan equation can be derived to compute this offset to derive the formulaconsider the - array illustrated in figure and observe the physical storage location within the - array for the first element in several of the rows element ( maps to position since it is the first element in both the abstract - and physical - arrays the first entry of the second row ( maps to position since it follows the first elements of the first row likewiseelement ( maps to position since it follows the first elements in the first two rows we could continue in the same fashion through all of the rowsbut you would soon notice the position for the first element of the ith row is physical storage of - array using column-major order column column column column column figure physical storage of sample - array (topin - array using columnmajor order (bottom |
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 - arraythe storage location of that element in the - array is computed as index (iji ( the column indexjis not only the offset within the given row but also the number of elements that must be skipped in the ith row to reach the jth column to see this formula in actionagain consider the - array from figure and assume we want to access element ( finding the target element within the - array requires skipping over the first complete rows of elementsn and the first elements within row plugging the indices into the equation from above results in an index position of which corresponds to the position of element ( within the - array used to physically store the - array similar equations can be derived for arrays of higher dimensions given - array of size the - array offset of element ( stored using row-major order will be index ( ( ( for each component (iin the subscriptthe equation computes the number of elements that must be skipped within the corresponding dimension for examplethe factor ( indicates the number of elements in single table of the cube when it' multiplied by we get the number of complete tables to skip and in turn the number of elements to skip in order to arrive at the first element of table |
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 notice pattern developing as the number of dimensions increase this pattern leads to general equation for computing the - array offset for element ( in within an -dimensional arrayindex( in in- fn- in ( where the fj values are the factors representing the number of elements to be skipped within the corresponding dimension and are computed using fn and fj dk < < ( = + the size of multi-dimensional array is fixed at the time it' created and cannot change during execution likewisethe several fj products used in the equation above will not change once the size of the array is set this can be used to our advantage to reduce the number of multiplications required to compute the element offsets instead of computing the products every time an element is accessedwe can compute and store the factor values and simply plug them into the equation when needed variable-length arguments the definition of the multiarray adt requires variable-length argument for the constructor and the two element access methods the number of arguments passed to each method is supposed to equal the number of dimensions in the array python functions and methods can be defined to accept variable number of argumentswhich is exactly what we need to implement the multiarray adt consider the following functionwhich accepts any number of arguments (assumed to be numerical in this exampleand then prints how many arguments were passed and the sum of those arguments |
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 outputnumber of arguments sum of the arguments number of arguments sum of the arguments number of arguments sum of the arguments the asterisk next to the argument name (*argstells python to accept any number of arguments and to combine them into tuple the tuple is then passed to the function and assigned to the formal argument marked with the asterisk note the asterisk is only used in the argument list to indicate that the function or method can accept any number of arguments it is not part of the argument name the len(operation can be applied to the tuple to determine the number of actual arguments passed to the function the individual argumentswhich are elements in the tuplecan be accessed by using the subscript notation or by iterating the collection implementing the multiarray to implement the multiarray adtthe elements of the multi-dimensional array can be stored in single - array in row-major order not only does this create fast and compact array structurebut it' also the actual technique used by most programming languages partial implementation of the multiarray class is provided in listing listing the array py module with the multiarray class implementation of the multiarray adt using - array class multiarray creates multi-dimensional array def __init__self*dimensions )assert len(dimensions "the array must have or more dimensions the variable argument tuple contains the dim sizes self _dims dimensions |
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 def numdimsself )return len(self _dimsreturns the length of the given dimension def lengthselfdim )assert dim > and dim len(self _dims),"dimension component out of range return self _dims[dim clears the array by setting all elements to the given value def clearselfvalue )self _elements clearvalue returns the contents of element (i_ i_ i_ndef __getitem__selfndxtuple )assert len(ndxtuple=self numdims()"invalid of array subscripts index self _computeindexndxtuple assert index is not none"array subscript out of range return self _elements[indexsets the contents of element (i_ i_ i_ndef __setitem__selfndxtuplevalue )assert len(ndxtuple=self numdims()"invalid of array subscripts index self _computeindexndxtuple assert index is not none"array subscript out of range self _elements[indexvalue computes the - array offset for element (i_ i_ i_nusing the equation i_ f_ i_ f_ i_n f_n def _computeindexselfidx )offset for in rangelen(idx)make sure the index components are within the legal range if idx[jself _dims[jreturn none else sum the product of i_j f_j offset +idx[jself _factors[jreturn offset computes the factor values used in the index equation def _computefactorsself ) |
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 is defined to accept variable-length argument as required in the adt definition the resulting tuple will contain the sizes of the individual dimensions and is assigned to the dims field the dimensionality of the array must be verified at the beginning of the constructor as the multiarray adt is meant for use with arrays of two dimensions or more the elements of the multi-dimensional array will be stored in - array the fixed size of the array can be computed as the product of the dimension lengths by traversing over the tuple containing the variable-length argument during the traversalthe precondition requiring all dimension lengths be greater than zero is also evaluated the array class defined earlier in the is used to create the storage array finallya - array is created and assigned to the factors field the size of the array is equal to the number of dimensions in the multi-dimensional array this array will be initialized to the factor values used in equation for computing the element offsets the actual computation and initialization is performed by the computefactors(helper methodwhich is left as an exercise sample instance of the multiarray class is illustrated in figure dims factors elements multiarray figure sample multiarray object for the - array from figure dimensionality and lengths in the multi-dimensional version of the arraythere is no single length value insteadeach dimension of the array has an associated size python' len(function cannot be used for this task since we must specify particular dimension to obtain its size insteadthe length(methodas shown in lines - of listing is used the method first verifies the given dimension index is between and nwhich is the legal range specified in the adt definition the size of the requested dimension is then returned using the appropriate value from the dims tuple the |
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 specified ( [ , ])python automatically stores the components in tuple in the order listed within the brackets and passes the tuple to the ndxtuple argument the contents of the ndxtuple are passed to the computeindex(helper method to compute the index offset within the - storage array the use of the helper method reduces the need for duplicate code that otherwise would be required in both element access methods the setitem operator method can be implemented in similar fashion the major difference is that this method requires second argument to receive the value to which an element is set and modifies the indicated element with the new value instead of returning value computing the offset the computeindex(helper methodshown in lines - of listing implements equation which computes the offset within the - storage array the method must also verify the subscript components are within the legal range of the dimension lengths if they are validthe offset is computed and returnedotherwisenone is returned to flag an invalid array index by returning none from the helper method instead of raising an exception within the methodbetter information can be provided to the programmer as to the exact element access operation that caused the error applicationsales reports lazymartinc is small regional chain department store with locations in several different cities and states the company maintains collection of sales records for the various items sold and would like to generate several different types of reports from this data one such reportfor exampleis the yearly sales by storeas illustrated in figure on the next pagewhile others could include total sales across all stores for specific month or specific item the sales data of the current calendar year for all of lazymart' stores is maintained as collection of entries in text file for examplethe following illustrates the first several lines of sample sales data text file |
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 four pieces of informationthe store numberthe month numberthe item numberand the sales amount for the given item in the given store during the given month for simplicitythe store and item numbers will consist of consecutive integer values in the range [ max]where max is the number of stores or items as extracted from the first two lines of the file the month is indicated by an integer in the range [ and the sales amount is floating-point value data organization while some reportslike the student report from are easy to produce by simply extracting the data and writing it to the reportothers require that we first organize the data in some meaningful way in order to extract the information needed that is definitely the case for this problemwhere we may need to produce many different reports from the same collection of data the ideal structure for storing the sales data is - arrayas shown in figure in which one dimension represents the storesanother represents the items sold in the storesand the last dimension represents each of the months in the calendar year the - array can be viewed as collection of spreadsheetsas illustrated in figure res sto items months figure the sales data stored in - array |
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 composed of consecutive integer values starting from we can easily represent each by unique index that is one less than the given number for examplethe data for january will be stored in column the data for february will be stored in column and so on likewisethe data for item number will be stored in row the data for item number will be stored in row and so on we leave the actual extraction of the data from text file as an exercise but for illustration purposeswe assume this step has been completed resulting in the creation and initialization of the - array as shown heresalesdata multiarray total sales by store with the data loaded from the file and stored in - arraywe can produce many different types of reports or extract various information from the sales data for examplesuppose we want to determine the total sales for given storewhich includes the sales figures of all items sold in that store for all months the following function computes this valuecompute the total sales of all items for all months in given store def totalsalesbystoresalesdatastore )subtract from the store since the array indices are less than the given store |
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 element in the spreadsheet containing the data for the given store if store equals this is equivalent to processing every element in the spreadsheet shown at the front of figure two nested loops are required since we must sum the values from each row and column contained in the given store spreadsheet the number of rows (dimension number and columns (dimension number can be obtained using the length(array method total sales by month nextsuppose we want to compute the total sales for given month that includes the sales figures of all items in all stores sold during that month this value can be computed using the following functioncompute the total sales of all items in all stores for given month def totalsalesbymonthsalesdatamonth )the month number must be offset by month accumulate the total sales for the given month total iterate over each store for in rangesalesdata length( )iterate over each item of the store for in rangesalesdata length( )total +salesdata[simreturn total this timethe two nested loops have to iterate over every row of every spreadsheet for the single column representing the given month if we use this function to compute the total sales for the month of januarythe elements of the - array that will be accessed are shown by the shaded area in figure (atotal sales by item another value that we can compute from the sales data in the - array is the total sales for given itemwhich includes the sales figures for all months and from all stores this is computed by the following function |
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( )total +salesdata[simreturn total the cells of the array that would be accessed when using this function to compute the total sales for item number are shown by the shaded area in figure (brememberthe sales for each item are stored in specific row of the array and the index of that row is one less than the item number since the indices start at st or es items items ( st or es ( months months figure the elements of the - array that must be accessed to compute the total sales(afor the month of january and (bfor item number monthly sales by store finallysuppose we want to compute the total monthly sales for each of the months at given store while the previous examples computed single valuethis task requires the computation of different totalsone for each month we can store the monthly totals in - array and return the structureas is done in the following function |
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( )sum iterate over the sales of each item sold during the month for in rangesalesdata length( )sum +salesdata[simstore the result in the corresponding month of the totals array totals[msum return the - array return totals figure illustrates the use of the - array for storing the individual monthly totals the shaded area shows the elements of the - array that are accessed when computing the total sales for the month of april at store number the monthly total will be stored at index position within the - array since that is the corresponding column in the - array for the month of april months store items totals figure the elements the - array that must be accessed to compute the monthly sales for store number |
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 used as shown here to create set initialized with the given valuess set add new operation to the set adt to test for proper subset given two setsa and ba is proper subset of bif is subset of and does not equal add the str(method to the set implementation to allow user to print the contents of the set the resulting string should look similar to that of listexcept you are to use curly braces to surround the elements add python operator methods to the set class that can be used to perform similar operations to those already defined by named methodsoperator method add (setbmul (setbsub (setblt (setbcurrent method union(setbinterset(setbdifference(setbissubsetof(setb add new operation keyarray(to the map class that returns an array containing all of the keys stored in the map the array of keys should be in no particular ordering add python operators to the map class that can be used to perform similar operations to those already defined by named methodsoperator method setitem (keyvaluegetitem (keycurrent method add(keyvaluevalueof(key design and implement the iterator class setiterator for use with the set adt implemented using list |
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 number of elements in each row other layouts are possible and sometimes required by problems in computer science for examplethe lower triangular array shown on the right is organized such that the rows are staggered with each successive row consisting of one more element than the previous row (aderive an equation that computes the total number of elements in the lower triangular table for table of size (bderive an index equation that maps an element of the lower triangular table onto one-dimensional array stored in row-major order complete the implementation of the multiarray class by implementing the helper method computefactors(programming projects in this we implemented the set adt using list implement the set adt using bag created from the bag class in your opinionwhich is the better implementationexplain your answer define new class named trianglearray to implement the lower triangular table described in exercise given collection of items stored in bagdesign linear time algorithm that determines the number of unique items in the collection write function that extracts the sales data from text file and builds the - array used to produce the various reports in section assume the data file has the format as described in the write menu-driven program that uses your function from the previous question to extract the sales data and can produce any of the following reports(aeach of the four types of reports described in the (bthe sales for single store similar to that shown in section with the data sorted by total sales (cthe total sales for each store sorted by total sales from largest to smallest (dthe total sales for each item sorted by item number |
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 programming language we then execute the program and time it using wall clock or the computer' internal clock the execution time is dependent on several factors firstthe amount of data that must be processed directly affects the execution time as the data set size increasesso does the execution time secondthe execution times can vary depending on the type of hardware and the time of day computer is used if we use multi-processmulti-user system to execute the programthe execution of other programs on the same machine can directly affect the execution time of our program finallythe choice of programming language and compiler used to implement an algorithm can also influence the execution time some compilers are better optimizers than others and some languages produce better optimized code than others thuswe need method to analyze an algorithm' efficiency independent of the implementation details complexity analysis to determine the efficiency of an algorithmwe can examine the solution itself and measure those aspects of the algorithm that most critically affect its execution time for examplewe can count the number of logical comparisonsdata interchangesor arithmetic operations consider the following algorithm for computing the sum of each row of an matrix and an overall sum of the entire matrixtotalsum version for in rangen rowsum[ for in rangen rowsum[irowsum[imatrix[ ,jtotalsum totalsum matrix[ , |
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 operationsthere are total of additions performed by the inner loop for each iteration of the outer loop the outer loop is also performed timesfor total of additions can we improve upon this algorithm to reduce the total number of addition operations performedconsider new version of the algorithm in which the second addition is moved out of the inner loop and modified to sum the entries in the rowsum array instead of individual elements of the matrix totalsum version for in rangen rowsum[ for in rangen rowsum[irowsum[imatrix[ ,jtotalsum totalsum rowsum[iin this versionthe inner loop is again executed timesbut this timeit only contains one addition operation that gives total of additions for each iteration of the outer loopbut the outer loop now contains an addition operator of its own to calculate the total number of additions for this versionwe take the additions performed by the inner loop and add one for the addition performed at the bottom of the outer loop this gives additions for each iteration of the outer loopwhich is performed times for total of additions if we compare the two resultsit' obvious the number of additions in the second version is less than the first for any greater than thusthe second version will execute faster than the firstbut the difference in execution times will not be significant the reason is that both algorithms execute on the same order of magnitudenamely thusas the size of increasesboth algorithms increase at approximately the same rate (though one is slightly better)as illustrated numerically in table and graphically in figure , , , , , , , , , , , , , , , , table growth rate comparisons for different input sizes |
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 the actual number of required steps for execution or the actual storage requirements in terms of variable-sized data sets the term big-owhich is derived from the expression "on the order of,is used to specify an algorithm' classification defining big- assume we have function (nthat represents the approximate number of steps required by an algorithm for an input of size for the second version of our algorithm in the previous sectionthis would be written as (nn nowsuppose there exists function (ndefined for the integers > such that for some constant cand some constant mt ( <cf (nfor all sufficiently large values of > thensuch an algorithm is said to have time-complexity ofor executes on the order off (nrelative to the number of operations it requires in other wordsthere is positive integer and constant (constant of proportionality such that for all >mt ( <cf (nthe |
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 computed to be ( if we let then < for result of ( for version twowe computed time of (nn againif we let then < for result of ( in this casethe choice of comes from the observation that when > we have < and < which satisfies the equation in the definition of big- the function (nn is not the only choice for satisfying the condition ( <cf (nwe could have said the algorithms had run time of ( or ( since the objectivehoweveris to find function (*that provides the tightest (lowestupper bound or limit for the run time of an algorithm the big- notation is intended to indicate an algorithm' efficiency for large values of there is usually little difference in the execution times of algorithms when is small constant of proportionality the constant of proportionality is only crucial when two algorithms have the same (nit usually makes no difference when comparing algorithms whose growth rates are of different magnitudes suppose we have two algorithmsl and with run times equal to and respectively has time-complexity of ( with and has time of (nwith even though has smaller constant of proportionalityl is still slower andin fact an order of magnitude slowerfor large values of thusf (ndominates the expression cf (nand the run time performance of the algorithm the differences between the run times of these two algorithms is shown numerically in table and graphically in figure constructing (ninstead of counting the number of logical comparisons or arithmetic operationswe evaluate an algorithm by considering every operation for simplicitywe assume that each basic operation or statementat the abstract leveltakes the same amount of time andthuseach is assumed to cost constant time the total number of |
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 become part of the constant of proportionality consider figure ( )which shows markup of version one of the algorithm from earlier the basic operations are marked with constant time while the loops are marked with the appropriate total number of iterations figure (bshows the same algorithm but with the constant steps omitted since these operations are independent of the data set size |
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 choosing the function the function (nused to categorize particular algorithm is chosen to be the dominant term within (nthat isthe term that is so large for big values of nthat we can ignore the other terms when computing big- value for examplein the expression log the term dominates the other terms since for > we have log < log < which leads to time-complexity of ( nowconsider the function ( and assume it is the polynomial that represents the exact number of instructions required to execute some algorithm for small values of (less than )the constant value dominates the functionbut what happens as gets largersay the term becomes the dominant termwith the other two becoming less significant in computing the final result classes of algorithms we will work with many different algorithms in this textbut most will have time-complexity selected from among common set of functionswhich are listed in table and illustrated graphically in figure algorithms can be classified based on their big- function the various classes are commonly named based upon the dominant term logarithmic algorithm is |
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 efficient since loga will increase more slowly than for many problems encountered in computer science will typically equal and thus we use the notation log to imply log logarithms of other bases will be explicitly stated polynomial algorithms with an efficiency expressed as polynomial of the form am nm am- nm- |
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 among the worst algorithms in terms of time-complexity evaluating python code as indicated earlierwhen evaluating the time complexity of an algorithm or code segmentwe assume that basic operations only require constant time but what exactly is basic operationthe basic operations include statements and function calls whose execution time does not depend on the specific values of the data that is used or manipulated by the given instruction for examplethe assignment statement is basic instruction since the time required to assign reference to the given variable is independent of the value or type of object specified on the righthand side of the sign the evaluation of arithmetic and logical expressions done and are basic instructionsagain since they require the same number of steps to perform the given operations regardless of the values of their operands the subscript operatorwhen used with python' sequence types (stringstuplesand listsis also basic instruction linear time examples nowconsider the following assignment statementy ex (nan assignment statement only requires constant timebut that is the time required to perform the actual assignment and does not include the time required to execute any function calls used on the righthand side of the assignment statement to determine the run time of the previous statementwe must know the cost of the function call ex (nthe time required by function call is the time it takes to execute the given function for exampleconsider the ex (functionwhich computes the sum of the integer values in the range [ )def ex )total for in rangen total + return total |
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 use of the print(functiononly require constant timeunless explicitly stated otherwise note the time required to execute loop depends on the number of iterations performed and the time needed to execute the loop body during each iteration in this casethe loop will be executed times and the loop body only requires constant time since it contains single basic instruction (note that the underlying mechanism of the for loop and the range(function are both ( we can compute the time required by the loop as (nn for result of (nbut what about the other statements in the functionthe first line of the function and the return statement only require constant time rememberit' common to omit the steps that only require constant time and instead focus on the critical operationsthose that contribute to the overall time in most instancesthis means we can limit our evaluation to repetition and selection statements and function and method calls since those have the greatest impact on the overall time of an algorithm since the loop is the only non-constant stepthe function ex (has run time of (nthat means the statement ex (nfrom earlier requires linear time nextconsider the following functionwhich includes two for loopsdef ex )count for in rangen count + for in rangen count + return count to evaluate the functionwe have to determine the time required by each loop the two loops each require (ntime as they are just like the loop in function ex (earlier if we combine the timesit yields (nn for result of (nquadratic time examples when presented with nested loopssuch as in the followingthe time required by the inner loop impacts the time of the outer loop def ex )count for in rangen for in rangen count + return count |
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 count + return count which has time-complexity of (nthe function contains nested loopbut the inner loop executes independent of the size variable since the inner loop executes constant number of timesit is constant time operation the outer loop executes timesresulting in linear run time the next example presents special case of nested loopsdef ex )count for in rangen for in rangei+ count + return count how many times does the inner loop executeit depends on the current iteration of the outer loop on the first iteration of the outer loopthe inner loop will execute one timeon the second iterationit executes two timeson the third iterationit executes three timesand so on until the last iteration when the inner loop will execute times the time required to execute the outer loop will be the number of times the increment statement count + is executed since the inner loop varies from to iterations by increments of the total number of times the increment statement will be executed is equal to the sum of the first positive integerst (nn( which results in quadratic time of ( logarithmic time examples the next example contains single loopbut notice the change to the modification step instead of incrementing (or decrementingby oneit cuts the loop variable in half each time through the loop def ex )count while > |
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 iterations ( given small numberit' easy to determine the number of loop iterations but how do we compute the number of iterations for any given value of nwhen the size of the input is reduced by half in each subsequent iterationthe number of iterations required to reach size of one will be equal to blog nc or the largest integer less than log nplus in our example of there are log or four iterations the logarithm to base of number nwhich is normally written as loga nis the power to which must be raised to equal nn ay thusfunction ex (requires (log ntime since many problems in computer science that repeatedly reduce the input size do so by halfit' not uncommon to use log to imply log when specifying the run time of an algorithm finallyconsider the following definition of function ex ()which calls ex (from within loop since the loop is executed times and function ex (requires logarithmic timeex (will have run time of ( log ndef ex )count for in rangen count +ex return count different cases some algorithms can have run times that are different orders of magnitude for different sets of inputs of the same size these algorithms can be evaluated for their bestworstand average cases algorithms that have different cases can typically be identified by the inclusion of an event-controlled loop or conditional statement consider the following examplewhich traverses list containing integer values to find the position of the first negative value note that for this problemthe input is the collection of values contained in the list def findnegintlist ) len(intlistfor in rangen if intlist[ return return none |
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 terminate in the normal fashion from having traversed all times in this casethe function requires (ntime this is known as the worst case since the function must examine every value in the list requiring the most number of steps now consider the case where the list contains negative value in the first elementl - findnegl there will only be one iteration of the loop since the test of the condition by the if statement will be true the first time through and the return statement inside the loop will be executed in this casethe findneg(function only requires ( time this is known as the best case since the function only has to examine the first value in the list requiring the least number of steps the average case is evaluated for an expected data set or how we expect the algorithm to perform on average for the findneg(functionwe would expect the search to iterate halfway through the list before finding the first negative valuewhich on average requires / iterations the average case is more difficult to evaluate because it' not always readily apparent what constitutes the average case for particular problem in generalwe are more interested in the worst case time-complexity of an algorithm as it provides an upper bound over all possible inputs in additionwe can compare the worst case run times of different implementations of an algorithm to determine which is the most efficient for any input evaluating the python list we defined several abstract data types for storing and using collections of data in the previous the next logical step is to analyze the operations of the various adts to determine their efficiency the result of this analysis depends on the efficiency of the python list since it was the primary data structure used to implement many of the earlier abstract data types the implementation details of the list were discussed in in this sectionwe use those details and evaluate the efficiency of some of the more common operations summary of the worst case run times are shown in table |
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 the built-in iteration for the list structurewhich accesses the items in sequential order starting with the first item consider the following code segmentwhich iterates over and computes the sum of the integer values in listsum for value in valuelist sum sum value to determine the order of complexity for this simple algorithmwe must first look at the internal implementation of the traversal iteration over the contiguous elements of - arraywhich is used to store the elements of listrequires count-controlled loop with an index variable whose value ranges over the indices of the subarray the list iteration above is equivalent to the followingsum for in rangelen(valuelistsum sum valuelist[iassuming the sequence contains itemsit' obvious the loop performs iterations since all of the operations within the loop only require constant timeincluding the element access operationa complete list traversal requires (ntime notethis time establishes minimum required for complete list traversal it can actually be higher if any operations performed during each iteration are worse than constant timeunlike this example list allocation creating listlike the creation of any objectis considered an operation whose time-complexity can be analyzed there are two techniques commonly used to |
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 elements requires list traversal since there are elements and traversal requires linear timethe allocation of vector with elements requires (ntime appending to list the append(operation adds new item to the end of the sequence if the underlying array used to implement the list has available capacity to add the new itemthe operation has best case time of ( since it only requires single element access in the worst casethere are no available slots and the array has to be expanded using the steps described in section creating the new larger array and destroying the old array can each be done in ( time to copy the contents of the old array to the new larger arraythe items have to be copied element by elementwhich requires (ntime combining the times from the three steps yields time of ( and worst case time of (nextending list the extend(operation adds the entire contents of source list to the end of the destination list this operation involves two listseach of which have their own collection of items that may be of different lengths to simplify the analysishoweverwe can assume both lists contain items when the destination list has sufficient capacity to store the new itemsthe entire contents of the source list can be copied in (ntime but if there is not sufficient capacitythe underlying array of the destination list has to be expanded to make room for the new items this expansion requires (ntime since there are currently items in the destination list after the expansionthe items in the source list are copied to the expanded arraywhich also requires (ntime thusin the worst case the extend operation requires (nn or (ntime inserting and removing items inserting new item into list is very similar to appending an item except the new item can be placed anywhere within the listpossibly requiring shift in elements an item can be removed from any element within listwhich may also involve shifting elements both of these operations require linear time in the worst casethe proof of which is left as an exercise |
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 to make room for the new valuehoweverthe append operation takes linear time when the array is expandedextra capacity is added that can be used to add more items without having to immediately expand the array thusthe number of times the append(operation actually requires linear time in sequence of operations depends on the strategy used to expand the underlying array consider the problem in which sequence of append operations are performed on an initially empty listwhere is power of list(for in range + appendi suppose the array is doubled in capacity each time it has to be expanded and assume the size of the underlying array for an empty list has the capacity for single item we can tally or compute the total running time for this problem by considering the time required for each individual append operation this approach is known as the aggregate method since it computes the total from the individual operations table illustrates the aggregate method when applied to sequence of append operations si represents the time required to physically store the ith value when there is an available slot in the array or immediately after the array has been expanded storing an item into an array element is constant time operation ei represents the time required to expand the array when it does not contain available capacity to store the item based on our assumptions related to the size of the arrayan expansion only occurs when is power of and the time incurred is based on the current size of the array ( while every append operation entails storage costrelatively few require an expansion cost note that as the size of increasesthe distance between append operations requiring an expansion also increases based on the tabulated results in table the total time required to perform sequence of append operations on an initially empty list is or just under this results from total storage cost (si of and total expansion cost (ei of it can be shown that for any nthe sum of the storage and expansion costssi ei will never be more than ( since there are relatively few expansion operationsthe expansion cost can be distributed across the sequence of operationsresulting in an amortized cost of ( / or ( for the append operation amortized analysis is the process of computing the time-complexity for sequence of operations by computing the average cost over the entire sequence for this technique to be appliedthe cost per operation must be known and it must |
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 append(method in long sequence of append operationsonly few instances require ( )while many of them are ( the amortized cost can only be used for long sequence of append operations if an algorithm used single append operationthe cost for that one operation is still (nin the worst case since we do not know if that' the instance that causes the underlying array to be expanded caution amortized cost is not average case time do not confuse amortized cost with that of average case time in average case analysisthe evaluation is done by computing an average over all possible inputs and sometimes requires the use of statistics amortized analysis computes an average cost over sequence of operations in which many of those operations are "cheapand relatively few are "expensivein terms of contributing to the overall time |
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 just evaluated the methods for that structure table provides summary of the worst case time-complexities for those operations implemented earlier in the text operation worst case set( ( len(so( in (ns add(xo(ns issubsetof(to( = ( union(to( traversal (ntable time-complexities for the set adt implementation using an unsorted list simple operations evaluating the constructor and length operation is straightforward as they simply call the corresponding list operation the contains methodwhich determines if an element is contained in the setuses the in operator to perform linear search over the elements stored in the underlying list the search operationwhich requires (ntimewill be presented in the next section and we postpone its analysis until that time the add(method also requires (ntime in the worst case since it uses the in operator to determine if the element is unique and the append(method to add the unique item to the underlying listboth of which require linear time in the worst case operations of two sets the remaining methods of the set class involve the use of two setswhich we label and bwhere is the self set and is the argument passed to the given method to simplify the analysiswe assume each set contains elements more complete analysis would involve the use of two variablesone for the size of each set but the analysis of this more specific case is sufficient for our purposes the issubsetof(method determines if is subset of it iterates over the elements of set aduring which the in operator is used to determine if the |
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 def removeselfelement )assert element in self"the element must be in the set self _theelements removeitem def __eq__selfsetb )if lenself !lensetb return false else return self issubsetofsetb def issubsetofselfsetb )for element in self if element not in setb return false return true def unionselfsetb )newset set(newset _theelements extendself _theelements for element in setb if element not in self newset _theelements appendelement return newset given element is member of set since there are repetitions of the loop and each use of the in operator requires (ntimethe issubsetof(method has quadratic run time of ( the set equality operation is also ( since it calls issubsetof(after determining the two sets are of equal size set union operation the set union(operation creates new setcthat contains all of the unique elements from both sets and it requires three steps the first step creates the new set cwhich can be done in constant time the second step fills set with the elements from set awhich requires (ntime since the extend(list method is used to add the elements to the last step iterates over the elements of set during which the in operator is used to determine if the given element |
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 and each iteration requires timethis step requires ( time combining the times for the three steps yields worst case time of ( applicationthe sparse matrix matrix containing large number of zero elements is called sparse matrix sparse matrices are very common in scientific applicationsespecially those dealing with systems of linear equations sparse matrix is formally defined to be an mxn matrix that contains non-zero elements such that mxn the - array data structure used to implement the matrix adt in works well for general matrices but when used to store huge sparse matriceslarge amounts of memory can be wasted and the operations can be inefficient since the zero elements are also stored in the - array consider the sample sparse matrix in figure is there different structure or organization we can use to store the elements of sparse matrix that does not waste spaceone approach is to organize and store the non-zero elements of the matrix within single list instead of - array figure sample sparse matrix with zero elements indicated with dots list-based implementation in this sectionwe define and implement class for storing and working with sparse matrices in which the non-zero elements are stored in list the operations of sparse matrix are the same as those for general matrix and many of them can be implemented in similar fashion as was done for the matrix class in listing this would be sufficient if our only objective was to reduce the storage costbut we can take advantage of only storing the non-zero elements to improve the efficiency of several of the sparse matrix operations the implementation of the sparsematrix class is provided in listing on the next page note the use of the new class name to distinguish this version from the original matrix adt and to indicate it is meant for use with sparse matrices sample instance of the class that corresponds to the sparse matrix from figure is illustrated in figure |
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 matrix def numrowsself )return self _numrows return the number of columns in the matrix def numcolsself )return self _numcols return the value of element (ij) [ ,jdef __getitem__selfndxtuple )set the value of element ( ,jto the value sx[ ,js def __setitem__selfndxtuplescalar )ndx self _findpositionndxtuple[ ]ndxtuple[ if ndx is not none if the element is found in the list if scalar ! self _elementlist[ndxvalue scalar else self _elementlist popndx else if the element is zero and not in the list if scalar ! element _matrixelementndxtuple[ ]ndxtuple[ ]scalar self _elementlist appendelement scale the matrix by the given scalar def scalebyselfscalar )for element in self _elementlist element value *scalar the additional methods should be placed here def __add__selfrhsmatrix )def __sub__selfrhsmatrix )def __mul__selfrhsmatrix )helper method used to find specific matrix element (row,colin the list of non-zero entries none is returned if the element is not found def _findpositionselfrowcol ) lenself _elementlist for in rangen if row =self _elementlist[irow and col =self _elementlist[icolreturn return the index of the element if found return none return none when the element is zero |
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 non-zero elements instances of the storage class contain not only the value for specific element but also the row and column indices indicating its location within the matrix the numrows and numcols fields are used to store the dimensions of the matrix this information cannot be obtained from the element list as was done with the array used in the implementation of the matrix adt in helper method since the element list only contains the non-zero entriesaccessing an individual element is no longer as simple as directly referencing an element of the rectangular grid insteadwe must search through the list to locate specific non-zero element the helper method findposition(performs this linear search by iterating through the element list looking for an entry with the given row and column indices if foundit returns the list index of the cell containing the elementotherwisenone is returned to indicate the absence of the element elementlist numrows numcols sparsematrix _matrixelement row col value figure list of matrixelement objects representing sparse matrix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.