id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
12,800 | class definitions class serves as the primary means for abstraction in object-oriented programming in pythonevery piece of data is represented as an instance of some class class provides set of behaviors in the form of member functions (also known as methods)with implementations that are common to all instances of that class class also serves as blueprint for its instanceseffectively determining the way that state information for each instance is represented in the form of attributes (also known as fieldsinstance variablesor data membersexamplecreditcard class as first examplewe provide an implementation of creditcard class based on the design we introduced in figure of section the instances defined by the creditcard class provide simple model for traditional credit cards they have identifying information about the customerbankaccount numbercredit limitand current balance the class restricts charges that would cause card' balance to go over its spending limitbut it does not charge interest or late payments (we revisit such themes in section our code begins in code fragment and continues in code fragment the construct begins with the keywordclassfollowed by the name of the classa colonand then an indented block of code that serves as the body of the class the body includes definitions for all methods of the class these methods are defined as functionsusing techniques introduced in section yet with special parameternamed selfthat serves to identify the particular instance upon which member is invoked the self identifier in pythonthe self identifier plays key role in the context of the creditcard classthere can presumably be many different creditcard instancesand each must maintain its own balanceits own credit limitand so on thereforeeach instance stores its own instance variables to reflect its current state syntacticallyself identifies the instance upon which method is invoked for exampleassume that user of our class has variablemy cardthat identifies an instance of the creditcard class when the user calls my card get balance)identifier selfwithin the definition of the get balance methodrefers to the card known as my card by the caller the expressionself balance refers to an instance variablenamed balancestored as part of that particular credit card' state |
12,801 | object-oriented programming class creditcard """ consumer credit card "" def init (selfcustomerbankacntlimit) """create new credit card instance the initial balance is zero customer the name of the customer ( john bowman bank the name of the bank ( california savings acnt the acount identifier ( limit credit limit (measured in dollars "" self customer customer self bank bank self account acnt self limit limit self balance def get customer(self) """return name of the customer "" return self customer def get bank(self) """return the bank name "" return self bank def get account(self) """return the card identifying number (typically stored as string"" return self account def get limit(self) """return current credit limit "" return self limit def get balance(self) """return current balance "" return self balance code fragment the beginning of the creditcard class definition (continued in code fragment |
12,802 | def charge(selfprice)"""charge given price to the cardassuming sufficient credit limit return true if charge was processedfalse if charge was denied ""if charge would exceed limitif price self balance self limitreturn false cannot accept charge elseself balance +price return true def make payment(selfamount)"""process customer payment that reduces balance ""self balance -amount code fragment the conclusion of the creditcard class definition (continued from code fragment these methods are indented within the class definition we draw attention to the difference between the method signature as declared within the class versus that used by caller for examplefrom user' perspective we have seen that the get balance method takes zero parametersyet within the class definitionself is an explicit parameter likewisethe charge method is declared within the class having two parameters (self and price)even though this method is called with one parameterfor exampleas my card charge( the interpretter automatically binds the instance upon which the method is invoked to the self parameter the constructor user can create an instance of the creditcard class using syntax ascc creditcardjohn doe st bank internallythis results in call to the specially named init method that serves as the constructor of the class its primary responsibility is to establish the state of newly created credit card object with appropriate instance variables in the case of the creditcard classeach object maintains five instance variableswhich we namecustomerbankaccountlimitand balance the initial values for the first four of those five are provided as explicit parameters that are sent by the user when instantiating the credit cardand assigned within the body of the constructor for examplethe commandself customer customerassigns the instance variable self customer to the parameter customernote that because customer is unqualified on the right-hand sideit refers to the parameter in the local namespace |
12,803 | encapsulation by the conventions described in section single leading underscore in the name of data membersuch as balanceimplies that it is intended as nonpublic users of class should not directly access such members as general rulewe will treat all data members as nonpublic this allows us to better enforce consistent state for all instances we can provide accessorssuch as get balanceto provide user of our class read-only access to trait if we wish to allow the user to change the statewe can provide appropriate update methods in the context of data structuresencapsulating the internal representation allows us greater flexibility to redesign the way class worksperhaps to improve the efficiency of the structure additional methods the most interesting behaviors in our class are charge and make payment the charge function typically adds the given price to the credit card balanceto reflect purchase of said price by the customer howeverbefore accepting the chargeour implementation verifies that the new purchase would not cause the balance to exceed the credit limit the make payment charge reflects the customer sending payment to the bank for the given amountthereby reducing the balance on the card we note that in the commandself balance -amountthe expression self balance is qualified with the self identifier because it represents an instance variable of the cardwhile the unqualified amount represents the local parameter error checking our implementation of the creditcard class is not particularly robust firstwe note that we did not explicitly check the types of the parameters to charge and make paymentnor any of the parameters to the constructor if user were to make call such as visa chargecandy )our code would presumably crash when attempting to add that parameter to the current balance if this class were to be widely used in librarywe might use more rigorous techniques to raise typeerror when facing such misuse (see section beyond the obvious type errorsour implementation may be susceptible to logical errors for exampleif user were allowed to charge negative pricesuch as visa charge(- )that would serve to lower the customer' balance this provides loophole for lowering balance without making payment of coursethis might be considered valid usage if modeling the credit received when customer returns merchandise to store we will explore some such issues with the creditcard class in the end-of-exercises |
12,804 | testing the class in code fragment we demonstrate some basic usage of the creditcard classinserting three cards into list named wallet we use loops to make some charges and paymentsand use various accessors to print results to the console these tests are enclosed within conditionalif name =__main__ :so that they can be embedded in the source code with the class definition using the terminology of section these tests provide method coverageas each of the methods is called at least oncebut it does not provide statement coverageas there is never case in which charge is rejected due to the credit limit this is not particular advanced from of testing as the output of the given tests must be manually audited in order to determine whether the class behaved as expected python has tools for more formal testing (see discussion of the unittest module in section )so that resulting values can be automatically compared to the predicted outcomeswith output generated only when an error is detected if name =__main__ wallet wallet append(creditcardjohn bowman california savings wallet append(creditcardjohn bowman california federal wallet append(creditcardjohn bowman california finance for val in range( ) wallet[ charge(val wallet[ charge( val wallet[ charge( val for in range( ) printcustomer wallet[cget customer) printbank wallet[cget bank) printaccount wallet[cget account) printlimit wallet[cget limit) printbalance wallet[cget balance) while wallet[cget balance wallet[cmake payment( printnew balance wallet[cget balance) printcode fragment testing the creditcard class |
12,805 | operator overloading and python' special methods python' built-in classes provide natural semantics for many operators for examplethe syntax invokes addition for numeric typesyet concatenation for sequence types when defining new classwe must consider whether syntax like should be defined when or is an instance of that class by defaultthe operator is undefined for new class howeverthe author of class may provide definition using technique known as operator overloading this is done by implementing specially named method in particularthe operator is overloaded by implementing method named add which takes the right-hand operand as parameter and which returns the result of the expression that isthe syntaxa bis converted to method call on object of the forma add (bsimilar specially named methods exist for other operators table provides comprehensive list of such methods when binary operator is applied to two instances of different typesas in love me python gives deference to the class of the left operand in this exampleit would effectively check if the int class provides sufficient definition for how to multiply an instance by stringvia the mul method howeverif that class does not implement such behaviorpython checks the class definition for the right-hand operandin the form of special method named rmul ( "right multiply"this provides way for new user-defined class to support mixed operations that involve an instance of an existing class (given that the existing class would presumably not have defined behavior involving this new classthe distinction between mul and rmul also allows class to define different semantics in casessuch as matrix multiplicationin which an operation is noncommutative (that isa may differ from anon-operator overloads in addition to traditional operator overloadingpython relies on specially named methods to control the behavior of various other functionalitywhen applied to user-defined classes for examplethe syntaxstr(foo)is formally call to the constructor for the string class of courseif the parameter is an instance of userdefined classthe original authors of the string class could not have known how that instance should be portrayed so the string constructor calls specially named methodfoo str )that must return an appropriate string representation similar special methods are used to determine how to construct an intfloator bool based on parameter from user-defined class the conversion to boolean value is particularly importantbecause the syntaxif foo:can be used even when foo is not formally boolean value (see section for user-defined classthat condition is evaluated by the special method foo bool |
12,806 | common syntax + - / / % < > & ^ | + - = + - ~ abs(aa< < > > = ! in [ka[kv del [ka(arg arg len(ahash(aiter(anext(abool(afloat(aint(arepr(areversed(astr( special method form add ( )alternatively sub ( )alternatively mul ( )alternatively truediv ( )alternatively floordiv ( )alternatively mod ( )alternatively pow ( )alternatively lshift ( )alternatively rshift ( )alternatively and ( )alternatively xor ( )alternatively or ( )alternatively iadd (ba isub (ba imul (ba pos neg invert abs lt (ba le (ba gt (ba ge (ba eq (ba ne (ba contains (va getitem (ka setitem ( ,va delitem (ka call (arg arg len hash iter next bool float int repr reversed str radd (arsub (armul (artruediv (arfloordiv (armod (arpow (arlshift (arrshift (arand (arxor (aror (atable overloaded operationsimplemented with python' special methods |
12,807 | several other top-level functions rely on calling specially named methods for examplethe standard way to determine the size of container type is by calling the top-level len function note well that the calling syntaxlen(foo)is not the traditional method-calling syntax with the dot operator howeverin the case of user-defined classthe top-level len function relies on call to specially named len method of that class that isthe call len(foois evaluated through method callfoo len when developing data structureswe will routinely define the len method to return measure of the size of the structure implied methods as general ruleif particular special method is not implemented in user-defined classthe standard syntax that relies upon that method will raise an exception for exampleevaluating the expressiona bfor instances of user-defined class without add or radd will raise an error howeverthere are some operators that have default definitions provided by pythonin the absence of special methodsand there are some operators whose definitions are derived from others for examplethe bool methodwhich supports the syntax if foo:has default semantics so that every object other than none is evaluated as true howeverfor container typesthe len method is typically defined to return the size of the container if such method existsthen the evaluation of bool(foois interpreted by default to be true for instances with nonzero lengthand false for instances with zero lengthallowing syntax such as if waitlistto be used to test whether there are one or more entries in the waitlist in section we will discuss python' mechanism for providing iterators for collections via the special methoditer with that saidif container class provides implementations for both len and getitem default iteration is provided automatically (using means we describe in section furthermoreonce an iterator is defineddefault functionality of contains is provided in section we drew attention to the distinction between expression is and expression =bwith the former evaluating whether identifiers and are aliases for the same objectand the latter testing notion of whether the two identifiers reference equivalent values the notion of "equivalencedepends upon the context of the classand semantics is defined with the eq method howeverif no implementation is given for eq the syntax = is legal with semantics of is bthat isan instance is equivalent to itself and no others we should caution that some natural implications are not automatically provided by python for examplethe eq method supports syntax =bbut providing that method does not affect the evaluation of syntax ! (the ne method should be providedtypically returning not ( =bas result similarlyproviding lt method supports syntax abut providing both lt and eq does not imply semantics for < |
12,808 | examplemultidimensional vector class to demonstrate the use of operator overloading via special methodswe provide an implementation of vector classrepresenting the coordinates of vector in multidimensional space for examplein three-dimensional spacewe might wish to represent vector with coordinates - although it might be tempting to directly use python list to represent those coordinatesa list does not provide an appropriate abstraction for geometric vector in particularif using liststhe expression [ - [ results in the list [ - when working with vectorsif - and one would expect the expressionu vto return three-dimensional vector with coordinates we therefore define vector classin code fragment that provides better abstraction for the notion of geometric vector internallyour vector relies upon an instance of listnamed coordsas its storage mechanism by keeping the internal list encapsulatedwe can enforce the desired public interface for instances of our class demonstration of supported behaviors includes the followingv vector( [ [- print( [ ] = + print(utotal for entry in vtotal +entry construct five-dimensional (based on use of setitem (also via setitem print (via getitem (via add print implicit iteration via len and getitem we implement many of the behaviors by trivially invoking similar behavior on the underlying list of coordinates howeverour implementation of add is customized assuming the two operands are vectors with the same lengththis method creates new vector and sets the coordinates of the new vector to be equal to the respective sum of the operandselements it is interesting to note that the class definitionas given in code fragment automatically supports the syntax [ - ]resulting in new vector that is the element-by-element "sumof the first vector and the list instance this is result of python' polymorphism literally"polymorphismmeans "many forms although it is tempting to think of the other parameter of our add method as another vector instancewe never declared it as such within the bodythe only behaviors we rely on for parameter other is that it supports len(otherand access to other[jthereforeour code executes when the right-hand operand is list of numbers (with matching length |
12,809 | object-oriented programming class vector """represent vector in multidimensional space "" def init (selfd) """create -dimensional vector of zeros "" self coords [ def len (self) """return the dimension of the vector "" return len(self coords def getitem (selfj) """return jth coordinate of vector "" return self coords[ def setitem (selfjval) """set jth coordinate of vector to given value "" self coords[jval def add (selfother) """return sum of two vectors "" if len(self!len(other)relies on len method raise valueerrordimensions must agree result vector(len(self)start with vector of zeros for in range(len(self)) result[jself[jother[ return result def eq (selfother) """return true if vector has same coordinates as other "" return self coords =other coords def ne (selfother) """return true if vector differs from other "" return not self =other rely on existing eq definition def str (self) """produce string representation of vector ""adapt list representation return code fragment definition of simple vector class |
12,810 | iterators iteration is an important concept in the design of data structures we introduced python' mechanism for iteration in section in shortan iterator for collection provides one key behaviorit supports special method named next that returns the next element of the collectionif anyor raises stopiteration exception to indicate that there are no further elements fortunatelyit is rare to have to directly implement an iterator class our preferred approach is the use of the generator syntax (also described in section )which automatically produces an iterator of yielded values python also helps by providing an automatic iterator implementation for any class that defines both len and getitem to provide an instructive example of low-level iteratorcode fragment demonstrates just such an iterator class that works on any collection that supports both len and getitem this class can be instantiated as sequenceiterator(datait operates by keeping an internal reference to the data sequenceas well as current index into the sequence each time next is calledthe index is incrementeduntil reaching the end of the sequence class sequenceiterator """an iterator for any of python sequence types "" def init (selfsequence) """create an iterator for the given sequence ""keep reference to the underlying data self seq sequence will increment to on first call to next self - def next (self) """return the next elementor else raise stopiteration error ""advance to next index self + if self len(self seq)return the data element return(self seq[self ] else raise stopiterationthere are no more elements def iter (self) """by conventionan iterator must return itself as an iterator "" return self code fragment an iterator class for any sequence type |
12,811 | examplerange class as the final example for this sectionwe develop our own implementation of class that mimics python' built-in range class before introducing our classwe discuss the history of the built-in version prior to python being releasedrange was implemented as functionand it returned list instance with elements in the specified range for examplerange( returned the list [ howevera typical use of the function was to support for-loop syntaxsuch as for in range( unfortunatelythis caused the instantiation and initialization of list with the range of numbers that was an unnecessarily expensive stepin terms of both time and memory usage the mechanism used to support ranges in python is entirely different (to be fairthe "newbehavior existed in python under the name xrangeit uses strategy known as lazy evaluation rather than creating new list instancerange is class that can effectively represent the desired range of elements without ever storing them explicitly in memory to better explore the built-in range classwe recommend that you create an instance as range( the result is relatively lightweight objectan instance of the range classthat has only few behaviors the syntax len(rwill report the number of elements that are in the given range ( in our examplea range also supports the getitem methodso that syntax [ reports the sixteenth element in the range (as [ is the first elementbecause the class supports both len and getitem it inherits automatic support for iteration (see section )which is why it is possible to execute for loop over range at this pointwe are ready to demonstrate our own version of such class code fragment provides class we name range (so as to clearly differentiate it from built-in rangethe biggest challenge in the implementation is properly computing the number of elements that belong in the rangegiven the parameters sent by the caller when constructing range by computing that value in the constructorand storing it as self lengthit becomes trivial to return it from the len method to properly implement call to getitem ( )we simply take the starting value of the range plus times the step size ( for = we return the start valuethere are few subtleties worth examining in the codeto properly support optional parameterswe rely on the technique described on page when discussing functional version of range we compute the number of elements in the range as max( (stop start step /stepit is worth testing this formula for both positive and negative step sizes the getitem method properly supports negative indices by converting an index - to len(self)- before computing the result |
12,812 | class range """ class that mimic the built-in range class "" def init (selfstartstop=nonestep= ) """initialize range instance semantics is similar to built-in range class "" if step = raise valueerrorstep cannot be if stop is nonespecial case of range( startstop start should be treated as if range( , calculate the effective length once self length max( (stop start step /step need knowledge of start and step (but not stopto support getitem self start start self step step def len (self) """return number of entries in the range "" return self length def getitem (selfk) """return entry at index (using standard interpretation if negative"" if +len(selfattempt to convert negative index if not < self length raise indexerrorindex out of range return self start self step code fragment our own implementation of range class |
12,813 | inheritance natural way to organize various structural components of software package is in hierarchical fashionwith similar abstract definitions grouped together in level-by-level manner that goes from specific to more general as one traverses up the hierarchy an example of such hierarchy is shown in figure using mathematical notationsthe set of houses is subset of the set of buildingsbut superset of the set of ranches the correspondence between levels is often referred to as an "is arelationshipas house is buildingand ranch is house building apartment low-rise apartment commercial building house high-rise apartment two-story house ranch skyscraper figure an example of an "is ahierarchy involving architectural buildings hierarchical design is useful in software developmentas common functionality can be grouped at the most general levelthereby promoting reuse of codewhile differentiated behaviors can be viewed as extensions of the general casein object-oriented programmingthe mechanism for modular and hierarchical organization is technique known as inheritance this allows new class to be defined based upon an existing class as the starting point in object-oriented terminologythe existing class is typically described as the base classparent classor superclasswhile the newly defined class is known as the subclass or child class there are two ways in which subclass can differentiate itself from its superclass subclass may specialize an existing behavior by providing new implementation that overrides an existing method subclass may also extend its superclass by providing brand new methods |
12,814 | python' exception hierarchy another example of rich inheritance hierarchy is the organization of various exception types in python we introduced many of those classes in section but did not discuss their relationship with each other figure illustrates (smallportion of that hierarchy the baseexception class is the root of the entire hierarchywhile the more specific exception class includes most of the error types that we have discussed programmers are welcome to define their own special exception classes to denote errors that may occur in the context of their application those user-defined exception types should be declared as subclasses of exception baseexception systemexit exception keyboardinterrupt lookuperror valueerror indexerror arithmeticerror keyerror zerodivisionerror figure portion of python' hierarchy of exception types extending the creditcard class to demonstrate the mechanisms for inheritance in pythonwe revisit the creditcard class of section implementing subclass thatfor lack of better namewe name predatorycreditcard the new class will differ from the original in two ways( if an attempted charge is rejected because it would have exceeded the credit limita $ fee will be chargedand ( there will be mechanism for assessing monthly interest charge on the outstanding balancebased upon an annual percentage rate (aprspecified as constructor parameter in accomplishing this goalwe demonstrate the techniques of specialization and extension to charge fee for an invalid charge attemptwe override the existing charge methodthereby specializing it to provide the new functionality (although the new version takes advantage of call to the overridden versionto provide support for charging interestwe extend the class with new method named process month |
12,815 | creditcard classfieldscustomer bank account balance limit behaviorsget customerget bankget accountmake payment(amountget balanceget limitcharge(pricepredatorycreditcard classfieldsapr behaviorsprocess monthcharge(pricefigure diagram of an inheritance relationship figure provides an overview of our use of inheritance in designing the new predatorycreditcard classand code fragment gives complete python implementation of that class to indicate that the new class inherits from the existing creditcard classour definition begins with the syntaxclass predatorycreditcard(creditcardthe init chargeand body of the new class provides three member functionsprocess month the init constructor serves very similar role to the original creditcard constructorexcept that for our new classthere is an extra parameter to specify the annual percentage rate the body of our new constructor relies upon making call to the inherited constructor to perform most of the initialization (in facteverything other than the recording of the percentage ratethe mechanism for calling the inherited constructor relies on the syntaxsuperspecificallyat line the command superinit (customerbankacntlimitcalls the init method that was inherited from the creditcard superclass note well that this method only accepts four parameters we record the apr value in new field named apr in similar fashionour predatorycreditcard class provides new implementation of the charge method that overrides the inherited method yetour implementation of the new method relies on call to the inherited methodwith syntax supercharge(priceat line the return value of that call designates whether |
12,816 | class predatorycreditcard(creditcard) """an extension to creditcard that compounds interest and fees "" def init (selfcustomerbankacntlimitapr) """create new predatory credit card instance the initial balance is zero customer the name of the customer ( john bowman bank the name of the bank ( california savings acnt the acount identifier ( limit credit limit (measured in dollars apr annual percentage rate ( for apr ""call super constructor superinit (customerbankacntlimit self apr apr def charge(selfprice) """charge given price to the cardassuming sufficient credit limit return true if charge was processed return false and assess fee if charge is denied "" success supercharge(pricecall inherited method if not successassess penalty self balance + return success caller expects return value def process month(self) """assess monthly interest on outstanding balance "" if self balance if positive balanceconvert apr to monthly multiplicative factor monthly factor pow( self apr / self balance monthly factor code fragment subclass of creditcard that assesses interest and fees |
12,817 | the charge was successful we examine that return value to decide whether to assess feeand in turn we return that value to the caller of methodso that the new version of charge has similar outward interface as the original the process month method is new behaviorso there is no inherited version upon which to rely in our modelthis method should be invoked by the bankonce each monthto add new interest charges to the customer' balance the most challenging aspect in implementing this method is making sure we have working knowledge of how an annual percentage rate translates to monthly rate we do not simply divide the annual rate by twelve to get monthly rate (that would be too predatoryas it would result in higher apr than advertisedthe correct computation is to take the twelfth-root of self aprand use that as multiplicative factor for exampleif the apr is (representing %)we compute and therefore charge interest per month in this wayeach $ of debt will amass $ of compounded interest in year protected members our predatorycreditcard subclass directly accesses the data member self balancewhich was established by the parent creditcard class the underscored nameby conventionsuggests that this is nonpublic memberso we might ask if it is okay that we access it in this fashion while general users of the class should not be doing soour subclass has somewhat privileged relationship with the superclass several object-oriented languages ( javac++draw distinction for nonpublic membersallowing declarations of protected or private access modes members that are declared as protected are accessible to subclassesbut not to the general publicwhile members that are declared as private are not accessible to either in this respectwe are using balance as if it were protected (but not privatepython does not support formal access controlbut names beginning with single underscore are conventionally akin to protectedwhile names beginning with double underscore (other than special methodsare akin to private in choosing to use protected datawe have created dependency in that our predatorycreditcard class might be compromised if the author of the creditcard class were to change the internal design note that we could have relied upon the public get balancemethod to retrieve the current balance within the process month method but the current design of the creditcard class does not afford an effective way for subclass to change the balanceother than by direct manipulation of the data member it may be tempting to use charge to add fees or interest to the balance howeverthat method does not allow the balance to go above the customer' credit limiteven though bank would presumably let interest compound beyond the credit limitif warranted if we were to redesign the original creditcard classwe might add nonpublic methodset balancethat could be used by subclasses to affect change without directly accessing the data member balance |
12,818 | hierarchy of numeric progressions as second example of the use of inheritancewe develop hierarchy of classes for iterating numeric progressions numeric progression is sequence of numberswhere each number depends on one or more of the previous numbers for examplean arithmetic progression determines the next number by adding fixed constant to the previous valueand geometric progression determines the next number by multiplying the previous value by fixed constant in generala progression requires first valueand way of identifying new value based on one or more previous values to maximize reusability of codewe develop hierarchy of classes stemming from general base class that we name progression (see figure technicallythe progression class produces the progression of whole numbers howeverthis class is designed to serve as the base class for other progression typesproviding as much common functionality as possibleand thereby minimizing the burden on the subclasses progression arithmeticprogression geometricprogression fibonacciprogression figure our hierarchy of progression classes our implementation of the basic progression class is provided in code fragment the constructor for this class accepts starting value for the progression ( by default)and initializes data memberself currentto that value the progression class implements the conventions of python iterator (see section )namely the special next and iter methods if user of the class creates progression as seq progression)each call to next(seqwill return subsequent element of the progression sequence it would also be possible to use for-loop syntaxfor value in seq:although we note that our default progression is defined as an infinite sequence to better separate the mechanics of the iterator convention from the core logic of advancing the progressionour framework relies on nonpublic method named advance to update the value of the self current field in the default implementationadvance adds one to the current valuebut our intent is that subclasses will override advance to provide different rule for computing the next entry for conveniencethe progression class also provides utility methodnamed print progressionthat displays the next values of the progression |
12,819 | object-oriented programming class progression """iterator producing generic progression default iterator produces the whole numbers "" def init (selfstart= ) """initialize current to the first value of the progression "" self current start def advance(self) """update self current to new value this should be overridden by subclass to customize progression by conventionif current is set to nonethis designates the end of finite progression "" self current + def next (self) """return the next elementor else raise stopiteration error ""our convention to end progression if self current is none raise stopiteration elserecord current value to return answer self current advance to prepare for next time self advance return answer return the answer def iter (self) """by conventionan iterator must return itself as an iterator "" return self def print progression(selfn) """print next values of the progression ""join(str(next(self)for in range( )) printcode fragment general numeric progression class |
12,820 | an arithmetic progression class our first example of specialized progression is an arithmetic progression while the default progression increases its value by one in each stepan arithmetic progression adds fixed constant to one term of the progression to produce the next for exampleusing an increment of for an arithmetic progression that starts at results in the sequence code fragment presents our implementation of an arithmeticprogression classwhich relies on progression as its base class the constructor for this new class accepts both an increment value and starting value as parametersalthough default values for each are provided by our conventionarithmeticprogression( produces the sequence and arithmeticprogression( produces the sequence the body of the arithmeticprogression constructor calls the super constructor to initialize the current data member to the desired start value then it directly establishes the new increment data member for the arithmetic progression the only remaining detail in our implementation is to override the advance method so as to add the increment to the current value class arithmeticprogression(progression)inherit from progression """iterator producing an arithmetic progression "" def init (selfincrement= start= ) """create new arithmetic progression increment the fixed constant to add to each term (default start the first term of the progression (default ""initialize base class superinit (start self increment increment override inherited version def advance(self) """update current value by adding the fixed increment "" self current +self increment code fragment class that produces an arithmetic progression |
12,821 | object-oriented programming geometric progression class our second example of specialized progression is geometric progressionin which each value is produced by multiplying the preceding value by fixed constantknown as the base of the geometric progression the starting point of geometric progression is traditionally rather than because multiplying by any factor results in as an examplea geometric progression with base proceeds as code fragment presents our implementation of geometricprogression class the constructor uses as default base and as default starting valuebut either of those can be varied using optional parameters class geometricprogression(progression)inherit from progression """iterator producing geometric progression "" def init (selfbase= start= ) """create new geometric progression base the fixed constant multiplied to each term (default start the first term of the progression (default "" superinit (start self base base override inherited version def advance(self) """update current value by multiplying it by the base value "" self current self base code fragment class that produces geometric progression fibonacci progression class as our final examplewe demonstrate how to use our progression framework to produce fibonacci progression we originally discussed the fibonacci series on page in the context of generators each value of fibonacci series is the sum of the two most recent values to begin the seriesthe first two values are conventionally and leading to the fibonacci series more generallysuch series can be generated from any two starting values for exampleif we start with values and the series proceeds as |
12,822 | class fibonacciprogression(progression) """iterator producing generalized fibonacci progression "" def init (selffirst= second= ) """create new fibonacci progression first the first term of the progression (default second the second term of the progression (default ""start progression at first superinit (firstfictitious value preceding the first self prev second first def advance(self) """update current value by taking sum of previous two "" self prevself current self currentself prev self current code fragment class that produces fibonacci progression we use our progression framework to define new fibonacciprogression classas shown in code fragment this class is markedly different from those for the arithmetic and geometric progressions because we cannot determine the next value of fibonacci series solely from the current one we must maintain knowledge of the two most recent values the base progression class already provides storage of the most recent value as the current data member our fibonacciprogression class introduces new membernamed prevto store the value that proceeded the current one with both previous values storedthe implementation of advance is relatively straightforward (we use simultaneous assignment similar to that on page howeverthe question arises as to how to initialize the previous value in the constructor the desired first and second values are provided as parameters to the constructor the first should be stored as current so that it becomes the first one that is reported looking aheadonce the first value is reportedwe will do an assignment to set the new current value (which will be the second value reported)equal to the first value plus the "previous by initializing the previous value to (second first)the initial advancement will set the new current value to first (second firstsecondas desired testing our progressions to complete our presentationcode fragment provides unit test for all of our progression classesand code fragment shows the output of that test |
12,823 | if name =__main__ printdefault progressionprogressionprint progression( printarithmetic progression with increment arithmeticprogression( print progression( printarithmetic progression with increment and start arithmeticprogression( print progression( printgeometric progression with default basegeometricprogressionprint progression( printgeometric progression with base geometricprogression( print progression( printfibonacci progression with default start valuesfibonacciprogressionprint progression( printfibonacci progression with start values and fibonacciprogression( print progression( code fragment unit tests for our progression classes default progression arithmetic progression with increment arithmetic progression with increment and start geometric progression with default base geometric progression with base fibonacci progression with default start values fibonacci progression with start values and code fragment output of the unit tests from code fragment |
12,824 | abstract base classes when defining group of classes as part of an inheritance hierarchyone technique for avoiding repetition of code is to design base class with common functionality that can be inherited by other classes that need it as an examplethe hierarchy from section includes progression classwhich serves as base class for three distinct subclassesarithmeticprogressiongeometricprogressionand fibonacciprogression although it is possible to create an instance of the progression base classthere is little value in doing so because its behavior is simply special case of an arithmeticprogression with increment the real purpose of the progression class was to centralize the implementations of behaviors that other progressions neededthereby streamlining the code that is relegated to those subclasses in classic object-oriented terminologywe say class is an abstract base class if its only purpose is to serve as base class through inheritance more formallyan abstract base class is one that cannot be directly instantiatedwhile concrete class is one that can be instantiated by this definitionour progression class is technically concretealthough we essentially designed it as an abstract base class in statically typed languages such as java and ++an abstract base class serves as formal type that may guarantee one or more abstract methods this provides support for polymorphismas variable may have an abstract base class as its declared typeeven though it refers to an instance of concrete subclass because there are no declared types in pythonthis kind of polymorphism can be accomplished without the need for unifying abstract base class for this reasonthere is not as strong tradition of defining abstract base classes in pythonalthough python' abc module provides support for defining formal abstract base class our reason for focusing on abstract base classes in our study of data structures is that python' collections module provides several abstract base classes that assist when defining custom data structures that share common interface with some of python' built-in data structures these rely on an object-oriented software design pattern known as the template method pattern the template method pattern is when an abstract base class provides concrete behaviors that rely upon calls to other abstract behaviors in that wayas soon as subclass provides definitions for the missing abstract behaviorsthe inherited concrete behaviors are well defined as tangible examplethe collections sequence abstract base class defines behaviors common to python' liststrand tuple classesas sequences that support element access via an integer index more sothe collections sequence class provides concrete implementations of methodscountindexand contains that can be inherited by any class that provides concrete implementations of both len and getitem for the purpose of illustrationwe provide sample implementation of such sequence abstract base class in code fragment |
12,825 | object-oriented programming from abc import abcmetaabstractmethod need these definitions class sequence(metaclass=abcmeta) """our own version of collections sequence abstract base class "" @abstractmethod def len (self) """return the length of the sequence "" @abstractmethod def getitem (selfj) """return the element at index of the sequence "" def contains (selfval) """return true if val found in the sequencefalse otherwise "" for in range(len(self)) if self[ =valfound match return true return false def index(selfval) """return leftmost index at which val is found (or raise valueerror"" for in range(len(self)) if self[ =valleftmost match return never found match raise valueerrorvalue not in sequence def count(selfval) """return the number of elements equal to given value "" = for in range(len(self)) if self[ =valfound match + return code fragment an abstract base class akin to collections sequence this implementation relies on two advanced python techniques the first is that we declare the abcmeta class of the abc module as metaclass of our sequence class metaclass is different from superclassin that it provides template for the class definition itself specificallythe abcmeta declaration assures that the constructor for the class raises an error |
12,826 | the second advanced technique is the use of the @abstractmethod decorator immediately before the len and getitem methods are declared that declares these two particular methods to be abstractmeaning that we do not provide an implementation within our sequence base classbut that we expect any concrete subclasses to support those two methods python enforces this expectationby disallowing instantiation for any subclass that does not override the abstract methods with concrete implementations the rest of the sequence class definition provides tangible implementations for other behaviorsunder the assumption that the abstract len and getitem methods will exist in concrete subclass if you carefully examine the source codethe implementations of methods contains indexand count do not rely on any assumption about the self instancesother than that syntax len(selfand self[jare supported (by special methods len and getitem respectivelysupport for iteration is automatic as wellas described in section in the remainder of this bookwe omit the formality of using the abc module if we need an "abstractbase classwe simply document the expectation that subclasses provide assumed functionalitywithout technical declaration of the methods as abstract but we will make use of the wonderful abstract base classes that are defined within the collections module (such as sequenceto use such classwe need only rely on standard inheritance techniques for exampleour range classfrom code fragment of section is an example of class that supports the len and getitem methods but that class does not support methods count or index had we originally declared it with sequence as superclassthen it would also inherit the count and index methods the syntax for such declaration would begin asclass range(collections sequence)finallywe emphasize that if subclass provides its own implementation of an inherited behaviors from base classthe new definition overrides the inherited one this technique can be used when we have the ability to provide more efficient implementation for behavior than is achieved by the generic approach as an examplethe general implementation of contains for sequence is based on loop used to search for the desired value for our range classthere is an opportunity for more efficient determination of containment for exampleit is evident that the expression in range( )should evaluate to trueeven without examining the individual elements of the rangebecause the range starts with zerohas an increment of and goes until millionit must include as that is multiple of that is between the start and stop values exercise - explores the goal of providing an implementation of range contains that avoids the use of (time-consumingloop |
12,827 | object-oriented programming namespaces and object-orientation namespace is an abstraction that manages all of the identifiers that are defined in particular scopemapping each name to its associated value in pythonfunctionsclassesand modules are all first-class objectsand so the "valueassociated with an identifier in namespace may in fact be functionclassor module in section we explored python' use of namespaces to manage identifiers that are defined with global scopeversus those defined within the local scope of function call in this sectionwe discuss the important role of namespaces in python' management of object-orientation instance and class namespaces we begin by exploring what is known as the instance namespacewhich manages attributes specific to an individual object for exampleeach instance of our creditcard class maintains distinct balancea distinct account numbera distinct credit limitand so on (even though some instances may coincidentally have equivalent balancesor equivalent credit limitseach credit card will have dedicated instance namespace to manage such values there is separate class namespace for each class that has been defined this namespace is used to manage members that are to be shared by all instances of classor used without reference to any particular instance for examplethe make payment method of the creditcard class from section is not stored independently by each instance of that class that member function is stored within the namespace of the creditcard class based on our definition from code fragments and the creditcard class namespace includes the functionsinit get customerget bankget accountget balanceget limitchargeand make payment our predatorycreditcard class has its own namespaceconinit chargeand taining the three methods we defined for that subclassprocess month figure provides portrayal of three such namespacesa class namespace containing methods of the creditcard classanother class namespace with methods of the predatorycreditcard classand finally single instance namespace for sample instance of the predatorycreditcard class we note that there are two different definitions of function named chargeone in the creditcard classand then the overriding method in the predatorycreditcard class in similar fashionthere are two distinct init implementations howeverprocess month is name that is only defined within the scope of the predatorycreditcard class the instance namespace includes all data members for the instance (including the apr member that is established by the predatorycreditcard constructor |
12,828 | function function function function function function function init get customer get bank get account make payment get balance get limit charge function john bowman california savings function function function init process month charge ( ( customer bank account balance limit apr (cfigure conceptual view of three namespaces(athe class namespace for creditcard(bthe class namespace for predatorycreditcard(cthe instance namespace for predatorycreditcard object how entries are established in namespace it is important to understand why member such as balance resides in credit card' instance namespacewhile member such as make payment resides in the class namespace the balance is established within the init method when new credit card instance is constructed the original assignment uses the syntaxself balance where self is an identifier for the newly constructed instance the use of self as qualifier for self balance in such an assignment causes the balance identifier to be added directly to the instance namespace when inheritance is usedthere is still single instance namespace per object for examplewhen an instance of the predatorycreditcard class is constructedthe apr attribute as well as attributes such as balance and limit all reside in that instance' namespacebecause all are assigned using qualified syntaxsuch as self apr class namespace includes all declarations that are made directly within the body of the class definition for exampleour creditcard class definition included the following structureclass creditcarddef make payment(selfamount)because the make payment function is declared within the scope of the creditcard classthat function becomes associated with the name make payment within the creditcard class namespace although member functions are the most typical types of entries that are declared in class namespacewe next discuss how other types of data valuesor even other classes can be declared within class namespace |
12,829 | class data members class-level data member is often used when there is some valuesuch as constantthat is to be shared by all instances of class in such caseit would be unnecessarily wasteful to have each instance store that value in its instance namespace as an examplewe revisit the predatorycreditcard introduced in section that class assesses $ fee if an attempted charge is denied because of the credit limit our choice of $ for the fee was somewhat arbitraryand our coding style would be better if we used named variable rather than embedding the literal value in our code oftenthe amount of such fee is determined by the bank' policy and does not vary for each customer in that casewe could define and use class data member as followsclass predatorycreditcard(creditcard)overlimit fee this is class-level member def charge(selfprice)success supercharge(priceif not successself balance +predatorycreditcard overlimit fee return success the data memberoverlimit feeis entered into the predatorycreditcard class namespace because that assignment takes place within the immediate scope of the class definitionand without any qualifying identifier nested classes it is also possible to nest one class definition within the scope of another class this is useful constructwhich we will exploit several times in this book in the implementation of data structures this can be done by using syntax such as class aclass bthe outer class the nested class in this caseclass is the nested class the identifier is entered into the namespace of class associated with the newly defined class we note that this technique is unrelated to the concept of inheritanceas class does not inherit from class nesting one class in the scope of another makes clear that the nested class exists for support of the outer class furthermoreit can help reduce potential name conflictsbecause it allows for similarly named class to exist in another context for examplewe will later introduce data structure known as linked list and will define nested node class to store the individual components of the list we will also introduce data structure known as tree that depends upon its own nested |
12,830 | node class these two structures rely on different node definitionsand by nesting those within the respective container classeswe avoid ambiguity another advantage of one class being nested as member of another is that it allows for more advanced form of inheritance in which subclass of the outer class overrides the definition of its nested class we will make use of that technique in section when specializing the nodes of tree structure dictionaries and the slots declaration by defaultpython represents each namespace with an instance of the built-in dict class (see section that maps identifying names in that scope to the associated objects while dictionary structure supports relatively efficient name lookupsit requires additional memory usage beyond the raw data that it stores (we will explore the data structure used to implement dictionaries in python provides more direct mechanism for representing instance namespaces that avoids the use of an auxiliary dictionary to use the streamlined representation for all instances of classthat class definition must provide class-level member named slots that is assigned to fixed sequence of strings that serve as names for instance variables for examplewith our creditcard classwe would declare the followingclass creditcardslots _customer _bank _account _balance _limit in this examplethe right-hand side of the assignment is technically tuple (see discussion of automatic packing of tuples in section when inheritance is usedif the base class declares slots subclass must also declare slots to avoid creation of instance dictionaries the declaration in the subclass should only include names of supplemental methods that are newly introduced for exampleour predatorycreditcard declaration would include the following declarationclass predatorycreditcard(creditcard)slots _apr in addition to the inherited members we could choose to use the slots declaration to streamline every class in this book howeverwe do not do so because such rigor would be atypical for python programs with that saidthere are few classes in this book for which we expect to have large number of instanceseach representing lightweight construct for examplewhen discussing nested classeswe suggest linked lists and trees as data structures that are often comprised of large number of individual nodes to promote greater efficiency in memory usagewe will use an explicit slots declaration in any nested classes for which we expect many instances |
12,831 | object-oriented programming name resolution and dynamic dispatch in the previous sectionwe discussed various namespacesand the mechanism for establishing entries in those namespaces in this sectionwe examine the process that is used when retrieving name in python' object-oriented framework when the dot operator syntax is used to access an existing membersuch as obj foothe python interpreter begins name resolution processdescribed as follows the instance namespace is searchedif the desired name is foundits associated value is used otherwise the class namespacefor the class to which the instance belongsis searchedif the name is foundits associated value is used if the name was not found in the immediate class namespacethe search continues upward through the inheritance hierarchychecking the class namespace for each ancestor (commonly by checking the superclass classthen its superclass classand so onthe first time the name is foundits associate value is used if the name has still not been foundan attributeerror is raised as tangible examplelet us assume that mycard identifies an instance of the predatorycreditcard class consider the following possible usage patterns mycard balance (or equivalentlyself balance from within method body)the balance method is found within the instance namespace for mycard mycard process month)the search begins in the instance namespacebut the name process month is not found in that namespace as resultthe predatorycreditcard class namespace is searchedin this casethe name is found and that method is called mycard make payment( )the search for the namemake paymentfails in the instance namespace and in the predatorycreditcard namespace the name is resolved in the namespace for superclass creditcard and thus the inherited method is called mycard charge( )the search for name charge fails in the instance namespace the next namespace checked is for the predatorycreditcard classbecause that is the true type of the instance there is definition for charge function in that classand so that is the one that is called in the last case shownnotice that the existence of charge function in the predatorycreditcard class has the effect of overriding the version of that function that exists in the creditcard namespace in traditional object-oriented terminologypython uses what is known as dynamic dispatch (or dynamic bindingto determineat run-timewhich implementation of function to call based upon the type of the object upon which it is invoked this is in contrast to some languages that use static dispatchingmaking compile-time decision as to which version of function to callbased upon the declared type of variable |
12,832 | shallow and deep copying in we emphasized that an assignment statement foo bar makes the name foo an alias for the object identified as bar in this sectionwe consider the task of making copy of an objectrather than an alias this is necessary in applications when we want to subsequently modify either the original or the copy in an independent manner consider scenario in which we manage various lists of colorswith each color represented by an instance of presumed color class we let identifier warmtones denote an existing list of such colors ( orangesbrownsin this applicationwe wish to create new list named palettewhich is copy of the warmtones list howeverwe want to subsequently be able to add additional colors to paletteor to modify or remove some of the existing colorswithout affecting the contents of warmtones if we were to execute the command palette warmtones this creates an aliasas shown in figure no new list is createdinsteadthe new identifier palette references the original list warmtones color palette list red green blue color red green blue figure two aliases for the same list of colors unfortunatelythis does not meet our desired criteriabecause if we subsequently add or remove colors from "palette,we modify the list identified as warmtones we can instead create new instance of the list class by using the syntaxpalette list(warmtonesin this casewe explicitly call the list constructorsending the first list as parameter this causes new list to be createdas shown in figure howeverit is what is known as shallow copy the new list is initialized so that its contents are precisely the same as the original sequence howeverpython' lists are referential (see page of section )and so the new list represents sequence of references to the same elements as in the first |
12,833 | warmtones list color palette list color red green blue red green blue figure shallow copy of list of colors this is better situation than our first attemptas we can legitimately add or remove elements from palette without affecting warmtones howeverif we edit color instance from the palette listwe effectively change the contents of warmtones although palette and warmtones are distinct liststhere remains indirect aliasingfor examplewith palette[ and warmtones[ as aliases for the same color instance we prefer that palette be what is known as deep copy of warmtones in deep copythe new copy references its own copies of those objects referenced by the original version (see figure warmtones color palette list red green blue color red green blue list color red green blue color red green blue figure deep copy of list of colors python' copy module to create deep copywe could populate our list by explicitly making copies of the original color instancesbut this requires that we know how to make copies of colors (rather than aliasingpython provides very convenient modulenamed copythat can produce both shallow copies and deep copies of arbitrary objects this module supports two functionsthe copy function creates shallow copy of its argumentand the deepcopy function creates deep copy of its argument after importing the modulewe may create deep copy for our exampleas shown in figure using the commandpalette copy deepcopy(warmtones |
12,834 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - give three examples of life-critical software applications - give an example of software application in which adaptability can mean the difference between prolonged lifetime of sales and bankruptcy - describe component from text-editor gui and the methods that it encapsulates - write python classflowerthat has three instance variables of type strintand floatthat respectively represent the name of the flowerits number of petalsand its price your class must include constructor method that initializes each variable to an appropriate valueand your class should include methods for setting the value of each typeand retrieving the value of each type - use the techniques of section to revise the charge and make payment methods of the creditcard class to ensure that the caller sends number as parameter - if the parameter to the make payment method of the creditcard class were negative numberthat would have the effect of raising the balance on the account revise the implementation so that it raises valueerror if negative value is sent - the creditcard class of section initializes the balance of new account to zero modify that class so that new account can be given nonzero balance using an optional fifth parameter to the constructor the four-parameter constructor syntax should continue to produce an account with zero balance - modify the declaration of the first for loop in the creditcard testsfrom code fragment so that it will eventually cause exactly one of the three credit cards to go over its credit limit which credit card is itr- implement the sub method for the vector class of section so that the expression - returns new vector instance representing the difference between two vectors - implement the neg method for the vector class of section so that the expression - returns new vector instance whose coordinates are all the negated values of the respective coordinates of |
12,835 | object-oriented programming - in section we note that our vector class supports syntax such as [ - ]in which the sum of vector and list returns new vector howeverthe syntax [ - is illegal explain how the vector class definition can be revised so that this syntax generates new vector - implement the mul method for the vector class of section so that the expression returns new vector with coordinates that are times the respective coordinates of - exercise - asks for an implementation of mul for the vector class of section to provide support for the syntax implement the rmul methodto provide additional support for syntax - implement the mul method for the vector class of section so that the expression returns scalar that represents the dot product of the vectorsthat isdi= ui vi - the vector class of section provides constructor that takes an integer dand produces -dimensional vector with all coordinates equal to another convenient form for creating new vector would be to send the constructor parameter that is some iterable type representing sequence of numbersand to create vector with dimension equal to the length of that sequence and coordinates equal to the sequence values for examplevector([ ]would produce three-dimensional vector with coordinates modify the constructor so that either of these forms is acceptablethat isif single integer is sentit produces vector of that dimension with all zerosbut if sequence of numbers is providedit produces vector with coordinates based on that sequence - our range classfrom section relies on the formula max( (stop start step /stepto compute the number of elements in the range it is not immediately evident why this formula provides the correct calculationeven if assuming positive step size justify this formulain your own words - draw class inheritance diagram for the following set of classesclass goat extends object and adds an instance variable tail and methods milkand jumpclass pig extends object and adds an instance variable nose and methods eat(foodand wallowclass horse extends object and adds instance variables height and colorand methods runand jumpclass racer extends horse and adds method raceclass equestrian extends horseadding an instance variable weight and methods trotand is trained |
12,836 | - give short fragment of python code that uses the progression classes from section to find the th value of fibonacci progression that starts with and as its first two values - when using the arithmeticprogression class of section with an increment of and start of how many calls to next can we make before we reach an integer of or largerr- what are some potential efficiency disadvantages of having very deep inheritance treesthat isa large set of classesabcand so onsuch that extends ac extends bd extends cetc - what are some potential efficiency disadvantages of having very shallow inheritance treesthat isa large set of classesabcand so onsuch that all of these classes extend single classzr- the collections sequence abstract base class does not provide support for comparing two sequences to each other modify our sequence class from code fragment to include definition for the eq methodso that expression seq =seq will return true precisely when the two sequences are element by element equivalent - in similar spirit to the previous problemaugment the sequence class with method lt to support lexicographic comparison seq seq creativity - suppose you are on the design team for new -book reader what are the primary classes and methods that the python software for your reader will needyou should include an inheritance diagram for this codebut you do not need to write any actual code your software architecture should at least include ways for customers to buy new booksview their list of purchased booksand read their purchased books - exercise - uses the mul method to support multiplying vector by numberwhile exercise - uses the mul method to support computing dot product of two vectors give single implementation of vector mul that uses run-time type checking to support both syntaxes and kwhere and designate vector instances and represents number - the sequenceiterator class of section provides what is known as forward iterator implement class named reversedsequenceiterator that serves as reverse iterator for any python sequence type the first call to next should return the last element of the sequencethe second call to next should return the second-to-last elementand so forth |
12,837 | - in section we note that our version of the range class has implicit support for iterationdue to its explicit support of both len and getitem the class also receives implicit support of the boolean test" in rfor range this test is evaluated based on forward iteration through the rangeas evidenced by the relative quickness of the test in range( versus in range( provide more efficient implementation of the contains method to determine whether particular value lies within given range the running time of your method should be independent of the length of the range - the predatorycreditcard class of section provides process month method that models the completion of monthly cycle modify the class so that once customer has made ten calls to charge in the current montheach additional call to that function results in an additional $ surcharge - modify the predatorycreditcard class from section so that customer is assigned minimum monthly paymentas percentage of the balanceand so that late fee is assessed if the customer does not subsequently pay that minimum amount before the next monthly cycle - at the close of section we suggest model in which the creditcard class supports nonpublic methodset balance( )that could be used by subclasses to affect change to the balancewithout directly accessing the balance data member implement such modelrevising both the creditcard and predatorycreditcard classes accordingly - write python class that extends the progression class so that each value in the progression is the absolute value of the difference between the previous two values you should include constructor that accepts pair of numbers as the first two valuesusing and as the defaults - write python class that extends the progression class so that each value in the progression is the square root of the previous value (note that you can no longer represent each value with an integer your constructor should accept an optional parameter specifying the start valueusing as default projects - write python program that inputs polynomial in standard algebraic notation and outputs the first derivative of that polynomial - write python program that inputs document and then outputs barchart plot of the frequencies of each alphabet character that appears in that document |
12,838 | - write set of python classes that can simulate an internet application in which one partyaliceis periodically creating set of packets that she wants to send to bob an internet process is continually checking if alice has any packets to sendand if soit delivers them to bob' computerand bob is periodically checking if his computer has packet from aliceandif sohe reads and deletes it - write python program to simulate an ecosystem containing two types of creaturesbears and fish the ecosystem consists of riverwhich is modeled as relatively large list each element of the list should be bear objecta fish objector none in each time stepbased on random processeach animal either attempts to move into an adjacent list location or stay where it is if two animals of the same type are about to collide in the same cellthen they stay where they arebut they create new instance of that type of animalwhich is placed in random empty ( previously nonelocation in the list if bear and fish collidehoweverthen the fish dies ( it disappearsp- write simulatoras in the previous projectbut add boolean gender field and floating-point strength field to each animalusing an animal class as base class if two animals of the same type try to collidethen they only create new instance of that type of animal if they are of different genders otherwiseif two animals of the same type and gender try to collidethen only the one of larger strength survives - write python program that simulates system that supports the functions of an -book reader you should include methods for users of your system to "buynew booksview their list of purchased booksand read their purchased books your system should use actual bookswhich have expired copyrights and are available on the internetto populate your set of available books for users of your system to "purchaseand read - develop an inheritance hierarchy based upon polygon class that has abstract methods areaand perimeterimplement classes trianglequadrilateralpentagonhexagonand octagon that extend this base classwith the obvious meanings for the areaand perimetermethods also implement classesisoscelestriangleequilateraltrianglerectangleand squarethat have the appropriate inheritance relationships finallywrite simple program that allows users to create polygons of the various types and input their geometric dimensionsand the program then outputs their area and perimeter for extra effortallow users to input polygons by specifying their vertex coordinates and be able to test if two such polygons are similar |
12,839 | notes for broad overview of developments in computer science and engineeringwe refer the reader to the computer science and engineering handbook [ for more information about the therac- incidentplease see the paper by leveson and turner [ the reader interested in studying object-oriented programming furtheris referred to the books by booch [ ]budd [ ]and liskov and guttag [ liskov and guttag also provide nice discussion of abstract data typesas does the survey paper by cardelli and wegner [ and the book by demurjian [ in the the computer science and engineering handbook [ design patterns are described in the book by gamma et al [ books with specific focus on object-oriented programming in python include those by goldwasser and letscher [ at the introductory leveland by phillips [ at more advanced level |
12,840 | algorithm analysis contents experimental studies moving beyond experimental analysis the seven functions used in this book comparing growth rates asymptotic analysis the "big-ohnotation comparative analysis examples of algorithm analysis simple justification techniques by example the "contraattack induction and loop invariants exercises |
12,841 | algorithm analysis in classic storythe famous mathematician archimedes was asked to determine if golden crown commissioned by the king was indeed pure goldand not part silveras an informant had claimed archimedes discovered way to perform this analysis while stepping into bath he noted that water spilled out of the bath in proportion to the amount of him that went in realizing the implications of this facthe immediately got out of the bath and ran naked through the city shouting"eurekaeureka!for he had discovered an analysis tool (displacement)whichwhen combined with simple scalecould determine if the king' new crown was good or not that isarchimedes could dip the crown and an equal-weight amount of gold into bowl of water to see if they both displaced the same amount this discovery was unfortunate for the goldsmithhoweverfor when archimedes did his analysisthe crown displaced more water than an equal-weight lump of pure goldindicating that the crown was notin factpure gold in this bookwe are interested in the design of "gooddata structures and algorithms simply puta data structure is systematic way of organizing and accessing dataand an algorithm is step-by-step procedure for performing some task in finite amount of time these concepts are central to computingbut to be able to classify some data structures and algorithms as "good,we must have precise ways of analyzing them the primary analysis tool we will use in this book involves characterizing the running times of algorithms and data structure operationswith space usage also being of interest running time is natural measure of "goodness,since time is precious resource--computer solutions should run as fast as possible in generalthe running time of an algorithm or data structure operation increases with the input sizealthough it may also vary for different inputs of the same size alsothe running time is affected by the hardware environment ( the processorclock ratememorydiskand software environment ( the operating systemprogramming languagein which the algorithm is implemented and executed all other factors being equalthe running time of the same algorithm on the same input data will be smaller if the computer hassaya much faster processor or if the implementation is done in program compiled into native machine code instead of an interpreted implementation we begin this by discussing tools for performing experimental studiesyet also limitations to the use of experiments as primary means for evaluating algorithm efficiency focusing on running time as primary measure of goodness requires that we be able to use few mathematical tools in spite of the possible variations that come from different environmental factorswe would like to focus on the relationship between the running time of an algorithm and the size of its input we are interested in characterizing an algorithm' running time as function of the input size but what is the proper way of measuring itin this we "roll up our sleevesand develop mathematical way of analyzing algorithms |
12,842 | experimental studies if an algorithm has been implementedwe can study its running time by executing it on various test inputs and recording the time spent during each execution simple approach for doing this in python is by using the time function of the time module this function reports the number of secondsor fractions thereofthat have elapsed since benchmark time known as the epoch the choice of the epoch is not significant to our goalas we can determine the elapsed time by recording the time just before the algorithm and the time just after the algorithmand computing their differenceas followsfrom time import time start time timerun algorithm end time timeelapsed end time start time record the starting time record the ending time compute the elapsed time we will demonstrate use of this approachin to gather experimental data on the efficiency of python' list class an elapsed time measured in this fashion is decent reflection of the algorithm efficiencybut it is by no means perfect the time function measures relative to what is known as the "wall clock because many processes share use of computer' central processing unit (or cpu)the elapsed time will depend on what other processes are running on the computer when the test is performed fairer metric is the number of cpu cycles that are used by the algorithm this can be determined using the clock function of the time modulebut even this measure might not be consistent if repeating the identical algorithm on the identical inputand its granularity will depend upon the computer system python includes more advanced modulenamed timeitto help automate such evaluations with repetition to account for such variance among trials because we are interested in the general dependence of running time on the size and structure of the inputwe should perform independent experiments on many different test inputs of various sizes we can then visualize the results by plotting the performance of each run of the algorithm as point with -coordinate equal to the input sizenand -coordinate equal to the running timet figure displays such hypothetical data this visualization may provide some intuition regarding the relationship between problem size and execution time for the algorithm this may lead to statistical analysis that seeks to fit the best function of the input size to the experimental data to be meaningfulthis analysis requires that we choose good sample inputs and test enough of them to be able to make sound statistical claims about the algorithm' running time |
12,843 | running time (ms input size figure results of an experimental study on the running time of an algorithm dot with coordinates ( ,tindicates that on an input of size nthe running time of the algorithm was measured as milliseconds (mschallenges of experimental analysis while experimental studies of running times are valuableespecially when finetuning production-quality codethere are three major limitations to their use for algorithm analysisexperimental running times of two algorithms are difficult to directly compare unless the experiments are performed in the same hardware and software environments experiments can be done only on limited set of test inputshencethey leave out the running times of inputs not included in the experiment (and these inputs may be importantan algorithm must be fully implemented in order to execute it to study its running time experimentally this last requirement is the most serious drawback to the use of experimental studies at early stages of designwhen considering choice of data structures or algorithmsit would be foolish to spend significant amount of time implementing an approach that could easily be deemed inferior by higher-level analysis |
12,844 | moving beyond experimental analysis our goal is to develop an approach to analyzing the efficiency of algorithms that allows us to evaluate the relative efficiency of any two algorithms in way that is independent of the hardware and software environment is performed by studying high-level description of the algorithm without need for implementation takes into account all possible inputs counting primitive operations to analyze the running time of an algorithm without performing experimentswe perform an analysis directly on high-level description of the algorithm (either in the form of an actual code fragmentor language-independent pseudo-codewe define set of primitive operations such as the followingassigning an identifier to an object determining the object associated with an identifier performing an arithmetic operation (for exampleadding two numberscomparing two numbers accessing single element of python list by index calling function (excluding operations executed within the functionreturning from function formallya primitive operation corresponds to low-level instruction with an execution time that is constant ideallythis might be the type of basic operation that is executed by the hardwarealthough many of our primitive operations may be translated to small number of instructions instead of trying to determine the specific execution time of each primitive operationwe will simply count how many primitive operations are executedand use this number as measure of the running time of the algorithm this operation count will correlate to an actual running time in specific computerfor each primitive operation corresponds to constant number of instructionsand there are only fixed number of primitive operations the implicit assumption in this approach is that the running times of different primitive operations will be fairly similar thusthe numbertof primitive operations an algorithm performs will be proportional to the actual running time of that algorithm measuring operations as function of input size to capture the order of growth of an algorithm' running timewe will associatewith each algorithma function (nthat characterizes the number of primitive operations that are performed as function of the input size section will introduce the seven most common functions that ariseand section will introduce mathematical framework for comparing functions to each other |
12,845 | focusing on the worst-case input an algorithm may run faster on some inputs than it does on others of the same size thuswe may wish to express the running time of an algorithm as the function of the input size obtained by taking the average over all possible inputs of the same size unfortunatelysuch an average-case analysis is typically quite challenging it requires us to define probability distribution on the set of inputswhich is often difficult task figure schematically shows howdepending on the input distributionthe running time of an algorithm can be anywhere between the worst-case time and the best-case time for examplewhat if inputs are really only of types "aor " "an average-case analysis usually requires that we calculate expected running times based on given input distributionwhich usually involves sophisticated probability theory thereforefor the remainder of this bookunless we specify otherwisewe will characterize running times in terms of the worst caseas function of the input sizenof the algorithm worst-case analysis is much easier than average-case analysisas it requires only the ability to identify the worst-case inputwhich is often simple alsothis approach typically leads to better algorithms making the standard of success for an algorithm to perform well in the worst case necessarily requires that it will do well on every input that isdesigning for the worst case leads to stronger algorithmic "muscles,much like track star who always practices by running up an incline running time (ms ms ms worst-case time average-case time ms best-case time ms ms input instance figure the difference between best-case and worst-case time each bar represents the running time of some algorithm on different possible input |
12,846 | the seven functions used in this book in this sectionwe briefly discuss the seven most important functions used in the analysis of algorithms we will use only these seven simple functions for almost all the analysis we do in this book in facta section that uses function other than one of these seven will be marked with star (to indicate that it is optional in addition to these seven fundamental functionsappendix contains list of other useful mathematical facts that apply in the analysis of data structures and algorithms the constant function the simplest function we can think of is the constant function this is the functionf (ncfor some fixed constant csuch as or that isfor any argument nthe constant function (nassigns the value in other wordsit does not matter what the value of isf (nwill always be equal to the constant value because we are most interested in integer functionsthe most fundamental constant function is ( and this is the typical constant function we use in this book note that any other constant functionf (nccan be written as constant times (nthat isf (ncg(nin this case as simple as it isthe constant function is useful in algorithm analysisbecause it characterizes the number of steps needed to do basic operation on computerlike adding two numbersassigning value to some variableor comparing two numbers the logarithm function one of the interesting and sometimes even surprising aspects of the analysis of data structures and algorithms is the ubiquitous presence of the logarithm functionf (nlogb nfor some constant this function is defined as followsx logb if and only if bx by definitionlogb the value is known as the base of the logarithm the most common base for the logarithm function in computer science is as computers store integers in binaryand because common operation in many algorithms is to repeatedly divide an input in half in factthis base is so common that we will typically omit it from the notation when it is that isfor uslog log |
12,847 | we note that most handheld calculators have button marked logbut this is typically for calculating the logarithm base- not base-two computing the logarithm function exactly for any integer involves the use of calculusbut we can use an approximation that is good enough for our purposes without calculus in particularwe can easily compute the smallest integer greater than or equal to logb (its so-called ceilinglogb for positive integernthis value is equal to the number of times we can divide by before we get number less than or equal to for examplethe evaluation of log is because (( / )/ )/ likewiselog is because (( / )/ )/ and log is because ((( / )/ )/ )/ < the following proposition describes several important identities that involve logarithms for any base greater than proposition (logarithm rules)given real numbers and we have logb (aclogb logb logb ( /clogb logb logb (ac logb logb logd alogd blogd alogd by conventionthe unparenthesized notation lognc denotes the value log(nc we use notational shorthandlogc nto denote the quantity(log ) in which the result of the logarithm is raised to power the above identities can be derived from converse rules for exponentiation that we will present on page we illustrate these identities with few examples example we demonstrate below some interesting applications of the logarithm rules from proposition (using the usual convention that the base of logarithm is if it is omittedlog( nlog log log nby rule log( / log log log by rule log log nby rule log log nby rule log (log )log (log )/ by rule log nlog nby rule as practical matterwe note that rule gives us way to compute the base-two logarithm on calculator that has base- logarithm buttonlogfor log log log |
12,848 | the linear function another simple yet important function is the linear functionf (nn that isgiven an input value nthe linear function assigns the value itself this function arises in algorithm analysis any time we have to do single basic operation for each of elements for examplecomparing number to each element of sequence of size will require comparisons the linear function also represents the best running time we can hope to achieve for any algorithm that processes each of objects that are not already in the computer' memorybecause reading in the objects already requires operations the -log- function the next function we discuss in this section is the -log- functionf (nn log nthat isthe function that assigns to an input the value of times the logarithm base-two of this function grows little more rapidly than the linear function and lot less rapidly than the quadratic functionthereforewe would greatly prefer an algorithm with running time that is proportional to log nthan one with quadratic running time we will see several important algorithms that exhibit running time proportional to the -log- function for examplethe fastest possible algorithms for sorting arbitrary values require time proportional to log the quadratic function another function that appears often in algorithm analysis is the quadratic functionf (nn that isgiven an input value nthe function assigns the product of with itself (in other words" squared"the main reason why the quadratic function appears in the analysis of algorithms is that there are many algorithms that have nested loopswhere the inner loop performs linear number of operations and the outer loop is performed linear number of times thusin such casesthe algorithm performs operations |
12,849 | nested loops and the quadratic function the quadratic function can also arise in the context of nested loops where the first iteration of loop uses one operationthe second uses two operationsthe third uses three operationsand so on that isthe number of operations is ( ( in other wordsthis is the total number of operations that will be performed by the nested loop if the number of operations performed inside the loop increases by one with each iteration of the outer loop this quantity also has an interesting history in german schoolteacher decided to keep his and -year-old pupils occupied by adding up the integers from to but almost immediately one of the children claimed to have the answerthe teacher was suspiciousfor the student had only the answer on his slate but the answer was correct and the studentcarl gaussgrew up to be one of the greatest mathematicians of his time we presume that young gauss used the following identity proposition for any integer > we have ( ( ( we give two "visualjustifications of proposition in figure + / ( (bfigure visual justifications of proposition both illustrations visualize the identity in terms of the total area covered by unit-width rectangles with heights in ( )the rectangles are shown to cover big triangle of area / (base and height nplus small triangles of area / each (base and height in ( )which applies only when is eventhe rectangles are shown to cover big rectangle of base / and height |
12,850 | the lesson to be learned from proposition is that if we perform an algorithm with nested loops such that the operations in the inner loop increase by one each timethen the total number of operations is quadratic in the number of timesnwe perform the outer loop to be fairthe number of operations is / / and so this is just over half the number of operations than an algorithm that uses operations each time the inner loop is performed but the order of growth is still quadratic in the cubic function and other polynomials continuing our discussion of functions that are powers of the inputwe consider the cubic functionf (nn which assigns to an input value the product of with itself three times this function appears less frequently in the context of algorithm analysis than the constantlinearand quadratic functions previously mentionedbut it does appear from time to time polynomials most of the functions we have listed so far can each be viewed as being part of larger class of functionsthe polynomials polynomial function has the formf (na ad nd where ad are constantscalled the coefficients of the polynomialand ad integer dwhich indicates the highest power in the polynomialis called the degree of the polynomial for examplethe following functions are all polynomialsf ( ( ( (nn (nn thereforewe could argue that this book presents just four important functions used in algorithm analysisbut we will stick to saying that there are sevensince the constantlinearand quadratic functions are too important to be lumped in with other polynomials running times that are polynomials with small degree are generally better than polynomial running times with larger degree |
12,851 | summations notation that appears again and again in the analysis of data structures and algorithms is the summationwhich is defined as followsb (if (af ( ( ( ) = where and are integers and < summations arise in data structure and algorithm analysis because the running times of loops naturally give rise to summations using summationwe can rewrite the formula of proposition as ii= ( likewisewe can write polynomial (nof degree with coefficients ad as (nai ni = thusthe summation notation gives us shorthand way of expressing sums of increasing terms that have regular structure the exponential function another function used in the analysis of algorithms is the exponential functionf (nbn where is positive constantcalled the baseand the argument is the exponent that isfunction (nassigns to the input argument the value obtained by multiplying the base by itself times as was the case with the logarithm functionthe most common base for the exponential function in algorithm analysis is for examplean integer word containing bits can represent all the nonnegative integers less than if we have loop that starts by performing one operation and then doubles the number of operations performed with each iterationthen the number of operations performed in the nth iteration is we sometimes have other exponents besides nhoweverhenceit is useful for us to know few handy rules for working with exponents in particularthe following exponent rules are quite helpful |
12,852 | proposition (exponent rules)given positive integers aband cwe have (ba ) bac ba bc ba+ ba /bc ba- for examplewe have the following ( ) * (exponent rule + (exponent rule / / - (exponent rule we can extend the exponential function to exponents that are fractions or real numbers and to negative exponentsas follows given positive integer kwe define / to be kth root of bthat isthe number such that rk for example / since likewise / and / this approach allows us to define any power whose exponent can be expressed as fractionfor ba/ (ba ) / by exponent rule for example / ( ) / / thusba/ is really just the cth root of the integral exponent ba we can further extend the exponential function to define bx for any real number xby computing series of numbers of the form ba/ for fractions / that get progressively closer and closer to any real number can be approximated arbitrarily closely by fraction /chencewe can use the fraction / as the exponent of to get arbitrarily close to bx for examplethe number is well defined finallygiven negative exponent dwe define bd / - which corresponds to applying exponent rule with and - for example - / / geometric sums suppose we have loop for which each iteration takes multiplicative factor longer than the previous one this loop can be analyzed using the following proposition proposition for any integer > and any real number such that and consider the summation ai an = (remembering that if this summation is equal to an+ - summations as shown in proposition are called geometric summationsbecause each term is geometrically larger than the previous one if for exampleeveryone working in computing should know that - for this is the largest integer that can be represented in binary notation using bits |
12,853 | comparing growth rates to sum uptable showsin ordereach of the seven common functions used in algorithm analysis constant logarithm log linear -log- log quadratic cubic exponential an table classes of functions here we assume that is constant (nideallywe would like data structure operations to run in times proportional to the constant or logarithm functionand we would like our algorithms to run in linear or -log- time algorithms with quadratic or cubic running times are less practicaland algorithms with exponential running times are infeasible for all but the smallest sized inputs plots of the seven functions are shown in figure exponential cubic quadratic -log- linear logarithmic constant figure growth rates for the seven fundamental functions used in algorithm analysis we use base for the exponential function the functions are plotted on log-log chartto compare the growth rates primarily as slopes even sothe exponential function grows too fast to display all its values on the chart the ceiling and floor functions one additional comment concerning the functions above is in order when discussing logarithmswe noted that the value is generally not an integeryet the running time of an algorithm is usually expressed by means of an integer quantitysuch as the number of operations performed thusthe analysis of an algorithm may sometimes involve the use of the floor function and ceiling functionwhich are defined respectively as followsxthe largest integer less than or equal to xthe smallest integer greater than or equal to |
12,854 | asymptotic analysis in algorithm analysiswe focus on the growth rate of the running time as function of the input size ntaking "big-pictureapproach for exampleit is often enough just to know that the running time of an algorithm grows proportionally to we analyze algorithms using mathematical notation for functions that disregards constant factors namelywe characterize the running times of algorithms by using functions that map the size of the inputnto values that correspond to the main factor that determines the growth rate in terms of this approach reflects that each basic step in pseudo-code description or high-level language implementation may correspond to small number of primitive operations thuswe can perform an analysis of an algorithm by estimating the number of primitive operations executed up to constant factorrather than getting bogged down in language-specific or hardware-specific analysis of the exact number of operations that execute on the computer as tangible examplewe revisit the goal of finding the largest element of python listwe first used this example when introducing for loops on page of section code fragment presents function named find max for this task def find max(data) """return the maximum element from nonempty python list "" biggest data[ the initial value to beat for val in datafor each value if val biggest if it is greater than the best so far biggest val we have found new best (so far return biggest when loop endsbiggest is the max code fragment function that returns the maximum value of python list this is classic example of an algorithm with running time that grows proportional to nas the loop executes once for each data elementwith some fixed number of primitive operations executing for each pass in the remainder of this sectionwe provide framework to formalize this claim the "big-ohnotation let (nand (nbe functions mapping positive integers to positive real numbers we say that (nis ( ( )if there is real constant and an integer constant > such that (nn this definition is often referred to as the "big-ohnotationfor it is sometimes pronounced as (nis big-oh of (nfigure illustrates the general definition |
12,855 | running time cg(nf(nn input size figure illustrating the "big-ohnotation the function (nis ( ( ))since (nn example the function is (njustificationby the big-oh definitionwe need to find real constant and an integer constant > such that it is easy to see that possible choice is and indeedthis is one of infinitely many choices available because there is trade-off between and for examplewe could rely on constants and the big-oh notation allows us to say that function (nis "less than or equal toanother function (nup to constant factor and in the asymptotic sense as grows toward infinity this ability comes from the fact that the definition uses "<=to compare (nto (ntimes constantcfor the asymptotic cases when > howeverit is considered poor taste to say ( < ( ( )),since the big-oh already denotes the "less-than-or-equal-toconcept likewisealthough commonit is not fully correct to say (no( ( )),with the usual understanding of the "=relationbecause there is no way to make sense of the symmetric statement" ( ( ) (nit is best to sayf (nis ( ( )alternativelywe can say (nis order of (nfor the more mathematically inclinedit is also correct to sayf (no( ( )),for the big-oh notationtechnically speakingdenotes whole collection of functions in this bookwe will stick to presenting big-oh statements as (nis ( ( )even with this interpretationthere is considerable freedom in how we can use arithmetic operations with the bigoh notationand with this freedom comes certain amount of responsibility |
12,856 | characterizing running times using the big-oh notation the big-oh notation is used widely to characterize running times and space bounds in terms of some parameter nwhich varies from problem to problembut is always defined as chosen measure of the "sizeof the problem for exampleif we are interested in finding the largest element in sequenceas with the find max algorithmwe should let denote the number of elements in that collection using the big-oh notationwe can write the following mathematically precise statement on the running time of algorithm find max (code fragment for any computer proposition the algorithmfind maxfor computing the maximum element of list of numbersruns in (ntime justificationthe initialization before the loop begins requires only constant number of primitive operations each iteration of the loop also requires only constant number of primitive operationsand the loop executes times thereforewe account for the number of primitive operations being for appropriate constants and that reflectrespectivelythe work performed during initialization and the loop body because each primitive operation runs in constant timewe have that the running time of algorithm find max on an input of size is at most constant times nthat iswe conclude that the running time of algorithm find max is (nsome properties of the big-oh notation the big-oh notation allows us to ignore constant factors and lower-order terms and focus on the main components of function that affect its growth example is ( justificationnote that <( ) cn for when > in factwe can characterize the growth rate of any polynomial function proposition if (nis polynomial of degree that isf (na ad nd and ad then (nis (nd justificationnote thatfor > we have < < <<nd hencea ad nd <(| | | |ad |nd we show that (nis (nd by defining | | |ad and |
12,857 | thusthe highest-degree term in polynomial is the term that determines the asymptotic growth rate of that polynomial we consider some additional properties of the big-oh notation in the exercises let us consider some further examples herefocusing on combinations of the seven fundamental functions used in algorithm design we rely on the mathematical fact that logn example log is ( justification log <( ) cn for when > example log is ( justification log example log is (log njustification log note that log is zero for that is why we use > in this case example + is ( justificationcase + hencewe can take and in this example log is (njustificationin this case log hencewe can take characterizing functions in simplest terms in generalwe should use the big-oh notation to characterize function as closely as possible while it is true that the function ( is ( or even ( )it is more accurate to say that (nis ( considerby way of analogya scenario where hungry traveler driving along long country road happens upon local farmer walking home from market if the traveler asks the farmer how much longer he must drive before he can find some foodit may be truthful for the farmer to say"certainly no longer than hours,but it is much more accurate (and helpfulfor him to say"you can find market just few minutes drive up this road thuseven with the big-oh notationwe should strive as much as possible to tell the whole truth it is also considered poor taste to include constant factors and lower-order terms in the big-oh notation for exampleit is not fashionable to say that the function is ( log )although this is completely correct we should strive instead to describe the function in the big-oh in simplest terms |
12,858 | the seven functions listed in section are the most common functions used in conjunction with the big-oh notation to characterize the running times and space usage of algorithms indeedwe typically use the names of these functions to refer to the running times of the algorithms they characterize sofor examplewe would say that an algorithm that runs in worst-case time log is quadratic-time algorithmsince it runs in ( time likewisean algorithm running in time at most log would be called linear-time algorithm big-omega just as the big-oh notation provides an asymptotic way of saying that function is "less than or equal toanother functionthe following notations provide an asymptotic way of saying that function grows at rate that is "greater than or equal tothat of another let (nand (nbe functions mapping positive integers to positive real numbers we say that (nis ( ( ))pronounced (nis big-omega of ( ),if (nis of ( ))that isthere is real constant and an integer constant > such that ( >cg( )for > this definition allows us to say asymptotically that one function is greater than or equal to anotherup to constant factor example log is ( log njustification log log (log > log for > hencewe can take and in this case big-theta in additionthere is notation that allows us to say that two functions grow at the same rateup to constant factors we say that (nis th( ( ))pronounced (nis big-theta of ( ),if (nis ( ( )and (nis ( ( )that isthere are real constants and and an integer constant > such that (nn example log log is th( log njustification log |
12,859 | comparative analysis suppose two algorithms solving the same problem are availablean algorithm awhich has running time of ( )and an algorithm bwhich has running time of ( which algorithm is betterwe know that is ( )which implies that algorithm is asymptotically better than algorithm balthough for small value of nb may have lower running time than we can use the big-oh notation to order classes of functions by asymptotic growth rate our seven functions are ordered by increasing growth rate in the following sequencethat isif function (nprecedes function (nin the sequencethen (nis ( ( )) log nnn log nn we illustrate the growth rates of the seven functions in table (see also figure from section log log table selected values of fundamental functions in algorithm analysis we further illustrate the importance of the asymptotic viewpoint in table this table explores the maximum size allowed for an input instance that is processed by an algorithm in second minuteand hour it shows the importance of good algorithm designbecause an asymptotically slow algorithm is beaten in the long run by an asymptotically faster algorithmeven if the constant factor for the asymptotically faster algorithm is worse running time (ms maximum problem size ( second minute hour , , , , , , table maximum size of problem that can be solved in second minuteand hourfor various running times measured in microseconds |
12,860 | the importance of good algorithm design goes beyond just what can be solved effectively on given computerhowever as shown in table even if we achieve dramatic speedup in hardwarewe still cannot overcome the handicap of an asymptotically slow algorithm this table shows the new maximum problem size achievable for any fixed amount of timeassuming algorithms with the given running times are now run on computer times faster than the previous one running time new maximum problem size + table increase in the maximum size of problem that can be solved in fixed amount of timeby using computer that is times faster than the previous one each entry is function of mthe previous maximum problem size some words of caution few words of caution about asymptotic notation are in order at this point firstnote that the use of the big-oh and related notations can be somewhat misleading should the constant factors they "hidebe very large for examplewhile it is true that the function is ( )if this is the running time of an algorithm being compared to one whose running time is log nwe should prefer the ( log )time algorithmeven though the linear-time algorithm is asymptotically faster this preference is because the constant factor which is called "one googol,is believed by many astronomers to be an upper bound on the number of atoms in the observable universe so we are unlikely to ever have real-world problem that has this number as its input size thuseven when using the big-oh notationwe should at least be somewhat mindful of the constant factors and lower-order terms we are "hiding the observation above raises the issue of what constitutes "fastalgorithm generally speakingany algorithm running in ( log ntime (with reasonable constant factorshould be considered efficient even an ( )-time function may be fast enough in some contextsthat iswhen is small but an algorithm running in ( time should almost never be considered efficient exponential running times there is famous story about the inventor of the game of chess he asked only that his king pay him grain of rice for the first square on the board grains for the second grains for the third for the fourthand so on it is an interesting test of programming skills to write program to compute exactly the number of grains of rice the king would have to pay |
12,861 | if we must draw line between efficient and inefficient algorithmsthereforeit is natural to make this distinction be that between those algorithms running in polynomial time and those running in exponential time that ismake the distinction between algorithms with running time that is (nc )for some constant and those with running time that is ( )for some constant like so many notions we have discussed in this sectionthis too should be taken with "grain of salt,for an algorithm running in ( time should probably not be considered "efficient even sothe distinction between polynomial-time and exponential-time algorithms is considered robust measure of tractability examples of algorithm analysis now that we have the big-oh notation for doing algorithm analysislet us give some examples by characterizing the running time of some simple algorithms using this notation moreoverin keeping with our earlier promisewe illustrate below how each of the seven functions given earlier in this can be used to characterize the running time of an example algorithm rather than use pseudo-code in this sectionwe give complete python implementations for our examples we use python' list class as the natural representation for an "arrayof values in we will fully explore the underpinnings of python' list classand the efficiency of the various behaviors that it supports in this sectionwe rely on just few of its behaviorsdiscussing their efficiencies as introduced constant-time operations given an instancenamed dataof the python list classa call to the functionlen(data)is evaluated in constant time this is very simple algorithm because the list class maintainsfor each listan instance variable that records the current length of the list this allows it to immediately report that lengthrather than take time to iteratively count each of the elements in the list using asymptotic notationwe say that this function runs in ( timethat isthe running time of this function is independent of the lengthnof the list another central behavior of python' list class is that it allows access to an arbitrary element of the list using syntaxdata[ ]for integer index because python' lists are implemented as array-based sequencesreferences to list' elements are stored in consecutive block of memory the jth element of the list can be foundnot by iterating through the list one element at timebut by validating the indexand using it as an offset into the underlying array in turncomputer hardware supports constant-time access to an element based on its memory address thereforewe say that the expression data[jis evaluated in ( time for python list |
12,862 | revisiting the problem of finding the maximum of sequence for our next examplewe revisit the find max algorithmgiven in code fragment on page for finding the largest value in sequence proposition on page claimed an (nrun-time for the find max algorithm consistent with our earlier analysis of syntax data[ ]the initialization uses ( time the loop executes timesand within each iterationit performs one comparison and possibly one assignment statement (as well as maintenance of the loop variablefinallywe note that the mechanism for enacting return statement in python uses ( time combining these stepswe have that the find max function runs in (ntime further analysis of the maximum-finding algorithm more interesting question about find max is how many times we might update the current "biggestvalue in the worst caseif the data is given to us in increasing orderthe biggest value is reassigned times but what if the input is given to us in random orderwith all orders equally likelywhat would be the expected number of times we update the biggest value in this caseto answer this questionnote that we update the current biggest in an iteration of the loop only if the current element is bigger than all the elements that precede it if the sequence is given to us in random orderthe probability that the jth element is the largest of the first elements is (assuming uniquenesshencethe expected number of times we update the biggest (including initializationis hn nj= jwhich is known as the nth harmonic number it turns out (see proposition that hn is (log nthereforethe expected number of times the biggest value is updated by find max on randomly ordered sequence is (log nprefix averages the next problem we consider is computing what are known as prefix averages of sequence of numbers namelygiven sequence consisting of numberswe want to compute sequence such that ajis the average of elements [ ]sj]for that isj aji= [ij+ computing prefix averages has many applications in economics and statistics for examplegiven the year-by-year returns of mutual fundordered from recent to pastan investor will typically want to see the fund' average annual returns for the most recent yearthe most recent three yearsthe most recent five yearsand so on likewisegiven stream of daily web usage logsa web site manager may wish to track average usage trends over various time periods we analyze three different implementations that solve this problem but with rather different running times |
12,863 | quadratic-time algorithm our first algorithm for computing prefix averagesnamed prefix average is shown in code fragment it computes every element of separatelyusing an inner loop to compute the partial sum def prefix average ( ) """return list such thatfor all ja[jequals average of [ ] [ "" len(screate new list of zeros [ for in range( ) total begin computing [ [ for in range( ) total + [ [jtotal ( + record the average return code fragment algorithm prefix average in order to analyze the prefix average algorithmwe consider the various steps that are executed the statementn len( )executes in constant timeas described at the beginning of section the statementa [ ncauses the creation and initialization of python list with length nand with all entries equal to zero this uses constant number of primitive operations per elementand thus runs in (ntime there are two nested for loopswhich are controlledrespectivelyby counters and the body of the outer loopcontrolled by counter jis executed timesfor thereforestatements total and [jtotal ( + are executed times each this implies that these two statementsplus the management of counter in the rangecontribute number of primitive operations proportional to nthat iso(ntime the body of the inner loopwhich is controlled by counter iis executed timesdepending on the current value of the outer loop counter thusstatement total + [ ]in the inner loopis executed times by recalling proposition we know that ( )/ which implies that the statement in the inner loop contributes ( time similar argument can be done for the primitive operations associated with maintaining counter iwhich also take ( time the running time of implementation prefix average is given by the sum of three terms the first and the second terms are ( )and the third term is ( by simple application of proposition the running time of prefix average is ( |
12,864 | our second implementation for computing prefix averagesprefix average is presented in code fragment def prefix average ( ) """return list such thatfor all ja[jequals average of [ ] [ "" len(screate new list of zeros [ for in range( ) [jsum( [ : + ]( + record the average return code fragment algorithm prefix average this approach is essentially the same high-level algorithm as in prefix average but we have replaced the inner loop by using the single expression sum( [ : + ]to compute the partial sums[ sjwhile the use of that function greatly simplifies the presentation of the algorithmit is worth asking how it affects the efficiency asymptoticallythis implementation is no better even though the expressionsum( [ : + ])seems like single commandit is function call and an evaluation of that function takes oj time in this context technicallythe computation of the slices[ : + ]also uses oj timeas it constructs new list instance for storage so the running time of prefix average is still dominated by series of steps that take time proportional to nand thus ( linear-time algorithm our final algorithmprefix averages is given in code fragment just as with our first two algorithmswe are interested in computingfor each jthe prefix sum [ [ sj]denoted as total in our codeso that we can then compute the prefix average [ =total ( howeverthere is key difference that results in much greater efficiency def prefix average ( ) """return list such thatfor all ja[jequals average of [ ] [ "" len(screate new list of zeros [ total compute prefix sum as [ [ for in range( ) total + [jupdate prefix sum to include [ [jtotal ( + compute average based on current sum return code fragment algorithm prefix average |
12,865 | in our first two algorithmsthe prefix sum is computed anew for each value of that contributed ojtime for each jleading to the quadratic behavior in algorithm prefix average we maintain the current prefix sum dynamicallyeffectively computing [ [ sjas total [ ]where value total is equal to the sum [ [ sj computed by the previous pass of the loop over the analysis of the running time of algorithm prefix average followsinitializing variables and total uses ( time initializing the list uses (ntime there is single for loopwhich is controlled by counter the maintenance of that counter by the range iterator contributes total of (ntime the body of the loop is executed timesfor thusstatements total + [jand [jtotal ( + are executed times each since each of these statements uses ( time per iterationtheir overall contribution is (ntime the running time of algorithm prefix average is given by the sum of the four terms the first is ( and the remaining three are (nby simple application of proposition the running time of prefix average is ( )which is much better than the quadratic time of algorithms prefix average and prefix average three-way set disjointness suppose we are given three sequences of numbersaband we will assume that no individual sequence contains duplicate valuesbut that there may be some numbers that are in two or three of the sequences the three-way set disjointness problem is to determine if the intersection of the three sequences is emptynamelythat there is no element such that ax band simple python function to determine this property is given in code fragment def disjoint (abc) """return true if there is no element common to all three lists "" for in for in for in if = = return false we found common value return true if we reach thissets are disjoint code fragment algorithm disjoint for testing three-way set disjointness this simple algorithm loops through each possible triple of values from the three sets to see if those values are equivalent if each of the original sets has size nthen the worst-case running time of this function is ( |
12,866 | we can improve upon the asymptotic performance with simple observation once inside the body of the loop over bif selected elements and do not match each otherit is waste of time to iterate through all values of looking for matching triple an improved solution to this problemtaking advantage of this observationis presented in code fragment def disjoint (abc) """return true if there is no element common to all three lists "" for in for in if =bonly check if we found match from and for in if = (and thus = = return false we found common value return true if we reach thissets are disjoint code fragment algorithm disjoint for testing three-way set disjointness in the improved versionit is not simply that we save time if we get lucky we claim that the worst-case running time for disjoint is ( there are quadratically many pairs (abto consider howeverif and are each sets of distinct elementsthere can be at most (nsuch pairs with equal to thereforethe innermost loopover cexecutes at most times to account for the overall running timewe examine the time spent executing each line of code the management of the for loop over requires (ntime the management of the for loop over accounts for total of ( timesince that loop is executed different times the test = is evaluated ( times the rest of the time spent depends upon how many matching (abpairs exist as we have notedthere are at most such pairsand so the management of the loop over cand the commands within the body of that loopuse at most ( time by our standard application of proposition the total time spent is ( element uniqueness problem that is closely related to the three-way set disjointness problem is the element uniqueness problem in the formerwe are given three collections and we presumed that there were no duplicates within single collection in the element uniqueness problemwe are given single sequence with elements and asked whether all elements of that collection are distinct from each other our first solution to this problem uses straightforward iterative algorithm the unique functiongiven in code fragment solves the element uniqueness problem by looping through all distinct pairs of indices kchecking if any of |
12,867 | algorithm analysis def unique ( ) """return true if there are no duplicate elements in sequence "" for in range(len( )) for in range( + len( )) if [ = [ ] return false found duplicate pair return true if we reach thiselements were unique code fragment algorithm unique for testing element uniqueness those pairs refer to elements that are equivalent to each other it does this using two nested for loopssuch that the first iteration of the outer loop causes iterations of the inner loopthe second iteration of the outer loop causes iterations of the inner loopand so on thusthe worst-case running time of this function is proportional to ( ( which we recognize as the familiar ( summation from proposition using sorting as problem-solving tool an even better algorithm for the element uniqueness problem is based on using sorting as problem-solving tool in this caseby sorting the sequence of elementswe are guaranteed that any duplicate elements will be placed next to each other thusto determine if there are any duplicatesall we need to do is perform single pass over the sorted sequencelooking for consecutive duplicates python implementation of this algorithm is as follows def unique ( ) """return true if there are no duplicate elements in sequence "" temp sorted(screate sorted copy of for in range( len(temp)) if [ - = [ ] return false found duplicate pair return true if we reach thiselements were unique code fragment algorithm unique for testing element uniqueness the built-in functionsortedas described in section produces copy of the original list with elements in sorted order it guarantees worst-case running time of ( log )see for discussion of common sorting algorithms once the data is sortedthe subsequent loop runs in (ntimeand so the entire unique algorithm runs in ( log ntime |
12,868 | simple justification techniques sometimeswe will want to make claims about an algorithmsuch as showing that it is correct or that it runs fast in order to rigorously make such claimswe must use mathematical languageand in order to back up such claimswe must justify or prove our statements fortunatelythere are several simple ways to do this by example some claims are of the generic form"there is an element in set that has property to justify such claimwe only need to produce particular in that has property likewisesome hard-to-believe claims are of the generic form"every element in set has property to justify that such claim is falsewe only need to produce particular from that does not have property such an instance is called counterexample example professor amongus claims that every number of the form is primewhen is an integer greater than professor amongus is wrong justificationto prove professor amongus is wrongwe find counterexample fortunatelywe need not look too farfor the "contraattack another set of justification techniques involves the use of the negative the two primary such methods are the use of the contrapositive and the contradiction the use of the contrapositive method is like looking through negative mirror to justify the statement "if is truethen is true,we establish that "if is not truethen is not trueinstead logicallythese two statements are the samebut the latterwhich is called the contrapositive of the firstmay be easier to think about example let and be integers if ab is eventhen is even or is even justificationto justify this claimconsider the contrapositive"if is odd and is oddthen ab is odd sosuppose and for some integers and then ab jk ( jk henceab is odd besides showing use of the contrapositive justification techniquethe previous example also contains an application of demorgan' law this law helps us deal with negationsfor it states that the negation of statement of the form " or qis "not and not likewiseit states that the negation of statement of the form " and qis "not or not |
12,869 | contradiction another negative justification technique is justification by contradictionwhich also often involves using demorgan' law in applying the justification by contradiction techniquewe establish that statement is true by first supposing that is false and then showing that this assumption leads to contradiction (such as or by reaching such contradictionwe show that no consistent situation exists with being falseso must be true of coursein order to reach this conclusionwe must be sure our situation is consistent before we assume is false example let and be integers if ab is oddthen is odd and is odd justificationlet ab be odd we wish to show that is odd and is odd sowith the hope of leading to contradictionlet us assume the oppositenamelysuppose is even or is even in factwithout loss of generalitywe can assume that is even (since the case for is symmetricthen for some integer henceab ( ) jb)that isab is even but this is contradictionab cannot simultaneously be odd and even thereforea is odd and is odd induction and loop invariants most of the claims we make about running time or space bound involve an integer parameter (usually denoting an intuitive notion of the "sizeof the problemmoreovermost of these claims are equivalent to saying some statement (nis true "for all > since this is making claim about an infinite set of numberswe cannot justify this exhaustively in direct fashion induction we can often justify claims such as those above as truehoweverby using the technique of induction this technique amounts to showing thatfor any particular > there is finite sequence of implications that starts with something known to be true and ultimately leads to showing that (nis true specificallywe begin justification by induction by showing that (nis true for (and possibly some other values kfor some constant kthen we justify that the inductive "stepis true for knamelywe show "if qjis true for all nthen (nis true the combination of these two pieces completes the justification by induction |
12,870 | proposition consider the fibonacci function ( )which is defined such that ( ( and (nf( ( for (see section we claim that ( justificationwe will show our claim is correct by induction base cases( < ( and ( induction step( suppose our claim is true for all consider (nsince (nf( ( moreoversince both and are less than nwe can apply the inductive assumption (sometimes called the "inductive hypothesis"to imply that ( - - since - - - - - let us do another inductive argumentthis time for fact we have seen before proposition (which is the same as proposition ii= ( justificationwe will justify this equality by induction base casen trivialfor ( )/ if induction stepn > assume the claim is true for consider - = = by the induction hypothesisthen ni= ( ) which we can simplify as ( ) ( we may sometimes feel overwhelmed by the task of justifying something true for all > we should rememberhoweverthe concreteness of the inductive technique it shows thatfor any particular nthere is finite step-by-step sequence of implications that starts with something true and leads to the truth about in shortthe inductive argument is template for building sequence of direct justifications |
12,871 | loop invariants the final justification technique we discuss in this section is the loop invariant to prove some statement about loop is correctdefine in terms of series of smaller statements lk where the initial claiml is true before the loop begins if - is true before iteration jthen will be true after iteration the final statementlk implies the desired statement to be true let us give simple example of using loop-invariant argument to justify the correctness of an algorithm in particularwe use loop invariant to justify that the functionfind (see code fragment )finds the smallest index at which element val occurs in sequence def find(sval) """return index such that [ =valor - if no such element "" len( = while if [ =val return match was found at index + return - code fragment algorithm for finding the first index at which given element occurs in python list to show that find is correctwe inductively define series of statementsl that lead to the correctness of our algorithm specificallywe claim the following is true at the beginning of iteration of the while loopl val is not equal to any of the first elements of this claim is true at the beginning of the first iteration of the loopbecause is and there are no elements among the first in (this kind of trivially true claim is said to hold vacuouslyin iteration jwe compare element val to element sjand return the index if these two elements are equivalentwhich is clearly correct and completes the algorithm in this case if the two elements val and sjare not equalthen we have found one more element not equal to val and we increment the index thusthe claim will be true for this new value of jhenceit is true at the beginning of the next iteration if the while loop terminates without ever returning an index in sthen we have that isln is true--there are no elements of equal to val thereforethe algorithm correctly returns - to indicate that val is not in |
12,872 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - graph the functions log and using logarithmic scale for the xand -axesthat isif the function value (nis yplot this as point with -coordinate at log and -coordinate at log - the number of operations executed by algorithms and is log and respectively determine such that is better than for > - the number of operations executed by algorithms and is and respectively determine such that is better than for > - give an example of function that is plotted the same on log-log scale as it is on standard scale - explain why the plot of the function nc is straight line with slope on log-log scale - what is the sum of all the even numbers from to nfor any positive integer nr- show that the following two statements are equivalent(athe running time of algorithm is always of ( )(bin the worst casethe running time of algorithm is of ( ) - order the following functions by asymptotic growth rate log log log log - show that if (nis of ( ))then ad(nis of ( ))for any constant - show that if (nis of ( )and (nis ( ( ))then the product ( ) (nis of ( ) ( ) - show that if (nis of ( )and (nis ( ( ))then (ne(nis of (ng( ) - show that if (nis of ( )and (nis ( ( ))then (ne(nis not necessarily of (ng( ) - show that if (nis of ( )and (nis ( ( ))then (nis ( ( ) - show that (maxf ( ) ( )}of (ng( ) |
12,873 | - show that (nis ( ( )if and only if (nis of ( ) - show that if (nis polynomial in nthen log (nis (log nr- show that ( ) is ( - show that + is ( - show that is ( log nr- show that is ( log nr- show that log is (nr- show that ( )is of ( ))if (nis positive nondecreasing function that is always greater than - give big-oh characterizationin terms of nof the running time of the example function shown in code fragment - give big-oh characterizationin terms of nof the running time of the example function shown in code fragment - give big-oh characterizationin terms of nof the running time of the example function shown in code fragment - give big-oh characterizationin terms of nof the running time of the example function shown in code fragment - give big-oh characterizationin terms of nof the running time of the example function shown in code fragment - for each function (nand time in the following tabledetermine the largest size of problem that can be solved in time if the algorithm for solving takes (nmicroseconds (one entry is already completed second log hour month century log - algorithm executes an (log )-time computation for each entry of an -element sequence what is its worst-case running timer- given an -element sequence salgorithm chooses log elements in at random and executes an ( )-time calculation for each what is the worst-case running time of algorithm br- given an -element sequence of integersalgorithm executes an ( )-time computation for each even number in sand an (log )-time computation for each odd number in what are the best-case and worstcase running times of algorithm |
12,874 | def example ( )"""return the sum of the elements in sequence "" len(stotal for in range( )loop from to - total + [jreturn total def example ( )"""return the sum of the elements with even index in sequence "" len(stotal for in range( )note the increment of total + [jreturn total def example ( )"""return the sum of the prefix sums of sequence "" len(stotal for in range( )loop from to - for in range( + )loop from to total + [kreturn total def example ( )"""return the sum of the prefix sums of sequence "" len(sprefix total for in range( )prefix + [jtotal +prefix return total def example (ab)assume that and have equal length """return the number of elements in equal to the sum of prefix sums in "" len(acount for in range( )loop from to - total for in range( )loop from to - for in range( + )loop from to total + [kif [ =totalcount + return count code fragment some sample algorithms for analysis |
12,875 | - given an -element sequence salgorithm calls algorithm on each element [ialgorithm runs in (itime when it is called on element [iwhat is the worst-case running time of algorithm dr- al and bob are arguing about their algorithms al claims his ( log )time method is always faster than bob' ( )-time method to settle the issuethey perform set of experiments to al' dismaythey find that if is the ( log )-time one better explain how this is possible - there is well-known city (which will go nameless herewhose inhabitants have the reputation of enjoying meal only if that meal is the best they have ever experienced in their life otherwisethey hate it assuming meal quality is distributed uniformly across person' lifedescribe the expected number of times inhabitants of this city are happy with their mealscreativity - assuming it is possible to sort numbers in ( log ntimeshow that it is possible to solve the three-way set disjointness problem in ( log ntime - describe an efficient algorithm for finding the ten largest elements in sequence of size what is the running time of your algorithmc- give an example of positive function (nsuch that (nis neither (nnor (nc- show that ni= is ( - show that ni= / (hinttry to bound this sum term by term with geometric progression - show that logb (nis th(log ( )if is constant - describe an algorithm for finding both the minimum and maximum of numbers using fewer than / comparisons (hintfirstconstruct group of candidate minimums and group of candidate maximums - bob built web site and gave the url only to his friendswhich he numbered from to he told friend number that he/she can visit the web site at most times now bob has counterckeeping track of the total number of visits to the site (but not the identities of who visitswhat is the minimum value for such that bob can know that one of his friends has visited his/her maximum allowed number of timesc- draw visual justification of proposition analogous to that of figure (bfor the case when is odd |
12,876 | - communication security is extremely important in computer networksand one way many network protocols achieve security is to encrypt messages typical cryptographic schemes for the secure transmission of messages over such networks are based on the fact that no efficient algorithms are known for factoring large integers henceif we can represent secret message by large prime number pwe can transmitover the networkthe number qwhere is another large prime number that acts as the encryption key an eavesdropper who obtains the transmitted number on the network would have to factor in order to figure out the secret message using factoring to figure out message is very difficult without knowing the encryption key to understand whyconsider the following naive factoring algorithmfor in range( , )if = return the secret message is pif divides suppose that the eavesdropper uses the above algorithm and has computer that can carry out in microsecond ( millionth of seconda division between two integers of up to bits each give an estimate of the time that it will take in the worst case to decipher the secret message if the transmitted message has bits what is the worst-case time complexity of the above algorithmsince the input to the algorithm is just one large number rassume that the input size is the number of bytes needed to store rthat isn (log )/ and that each division takes time (nc- sequence contains unique integers in the range [ ]that isthere is one number from this range that is not in design an ( )time algorithm for finding that number you are only allowed to use ( additional space besides the sequence itself - al says he can prove that all sheep in flock are the same colorbase caseone sheep it is clearly the same color as itself induction stepa flock of sheep take sheepaout the remaining are all the same color by induction now put sheep back in and take out different sheepb by inductionthe sheep (now with aare all the same color thereforeall the sheep in the flock are the same color what is wrong with al' "justification" - let be set of lines in the plane such that no two are parallel and no three meet in the same point showby inductionthat the lines in determine th( intersection points |
12,877 | - consider the following "justificationthat the fibonacci functionf( (see proposition is ( )base case ( < ) ( and ( induction step ( )assume claim true for consider (nf( ( by inductionf( is ( and ( is ( thenf(nis (( ( ))by the identity presented in exercise - thereforef(nis (nwhat is wrong with this "justification" - consider the fibonacci functionf( (see proposition show by induction that (nis (( / ) - let (xbe polynomial of degree nthat isp(xni= ai xi (adescribe simple ( )-time algorithm for computing ( (bdescribe an ( log )-time algorithm for computing ( )based upon more efficient calculation of xi (cnow consider rewriting of (xas (xa ( ( ( (an- xan )))which is known as horner' method using the big-oh notationcharacterize the number of arithmetic operations this method executes - show that the summation ni= log is ( log nc- show that the summation ni= log is ( log nc- an evil king has bottles of wineand spy has just poisoned one of them unfortunatelythey do not know which one it is the poison is very deadlyjust one drop diluted even billion to one will still kill even soit takes full month for the poison to take effect design scheme for determining exactly which one of the wine bottles was poisoned in just one month' time while expending (log ntaste testers - sequence contains integers taken from the interval [ ]with repetitions allowed describe an efficient algorithm for determining an integer value that occurs the most often in what is the running time of your algorithmprojects - perform an experimental analysis of the three algorithms prefix average prefix average and prefix average from section visualize their running times as function of the input size with log-log chart - perform an experimental analysis that compares the relative running times of the functions shown in code fragment |
12,878 | - perform experimental analysis to test the hypothesis that python' sorted method runs in ( log ntime on average - for each of the three algorithmsunique unique and unique which solve the element uniqueness problemperform an experimental analysis to determine the largest value of such that the given algorithm runs in one minute or less notes the big-oh notation has prompted several comments about its proper use [ knuth [ defines it using the notation (no( ( ))but says this "equalityis only "one way we have chosen to take more standard view of equality and view the big-oh notation as setfollowing brassard [ the reader interested in studying average-case analysis is referred to the book by vitter and flajolet [ for some additional mathematical toolsplease refer to appendix |
12,879 | recursion contents illustrative examples the factorial function drawing an english ruler binary search file systems analyzing recursive algorithms recursion run amok maximum recursive depth in python further examples of recursion linear recursion binary recursion multiple recursion designing recursive algorithms eliminating tail recursion exercises |
12,880 | one way to describe repetition within computer program is the use of loopssuch as python' while-loop and for-loop constructs described in section an entirely different way to achieve repetition is through process known as recursion recursion is technique by which function makes one or more calls to itself during executionor by which data structure relies upon smaller instances of the very same type of structure in its representation there are many examples of recursion in art and nature for examplefractal patterns are naturally recursive physical example of recursion used in art is in the russian matryoshka dolls each doll is either made of solid woodor is hollow and contains another matryoshka doll inside it in computingrecursion provides an elegant and powerful alternative for performing repetitive tasks in facta few programming languages ( schemesmalltalkdo not explicitly support looping constructs and instead rely directly on recursion to express repetition most modern programming languages support functional recursion using the identical mechanism that is used to support traditional forms of function calls when one invocation of the function make recursive callthat invocation is suspended until the recursive call completes recursion is an important technique in the study of data structures and algorithms we will use it prominently in several later of this book (most notably and in this we begin with the following four illustrative examples of the use of recursionproviding python implementation for each the factorial function (commonly denoted as !is classic mathematical function that has natural recursive definition an english ruler has recursive pattern that is simple example of fractal structure binary search is among the most important computer algorithms it allows us to efficiently locate desired value in data set with upwards of billions of entries the file system for computer has recursive structure in which directories can be nested arbitrarily deeply within other directories recursive algorithms are widely used to explore and manage these file systems we then describe how to perform formal analysis of the running time of recursive algorithm and we discuss some potential pitfalls when defining recursions in the balance of the we provide many more examples of recursive algorithmsorganized to highlight some common forms of design |
12,881 | illustrative examples the factorial function to demonstrate the mechanics of recursionwe begin with simple mathematical example of computing the value of the factorial function the factorial of positive integer ndenoted !is defined as the product of the integers from to if then nis defined as by convention more formallyfor any integer > ( ( if if > for example the factorial function is important because it is known to equal the number of ways in which distinct items can be arranged into sequencethat isthe number of permutations of items for examplethe three characters aband can be arranged in waysabcacbbacbcacaband cba there is natural recursive definition for the factorial function to see thisobserve that ( more generallyfor positive integer nwe can define nto be ( )this recursive definition can be formalized as ( )if if > this definition is typical of many recursive definitions firstit contains one or more base caseswhich are defined nonrecursively in terms of fixed quantities in this casen is the base case it also contains one or more recursive caseswhich are defined by appealing to the definition of the function being defined recursive implementation of the factorial function recursion is not just mathematical notationwe can use recursion to design python implementation of factorial functionas shown in code fragment def factorial( ) if = return else return factorial( - code fragment recursive implementation of the factorial function |
12,882 | this function does not use any explicit loops repetition is provided by the repeated recursive invocations of the function there is no circularity in this definitionbecause each time the function is invokedits argument is smaller by oneand when base case is reachedno further recursive calls are made we illustrate the execution of recursive function using recursion trace each entry of the trace corresponds to recursive call each new recursive function call is indicated by downward arrow to new invocation when the function returnsan arrow showing this return is drawn and the return value may be indicated alongside this arrow an example of such trace for the factorial function is shown in figure return factorial( return = factorial( return = factorial( return = factorial( return factorial( figure recursion trace for the call factorial( recursion trace closely mirrors the programming language' execution of the recursion in pythoneach time function (recursive or otherwiseis calleda structure known as an activation record or frame is created to store information about the progress of that invocation of the function this activation record includes namespace for storing the function call' parameters and local variables (see section for discussion of namespaces)and information about which command in the body of the function is currently executing when the execution of function leads to nested function callthe execution of the former call is suspended and its activation record stores the place in the source code at which the flow of control should continue upon return of the nested call this process is used both in the standard case of one function calling different functionor in the recursive case in which function invokes itself the key point is that there is different activation record for each active call |
12,883 | drawing an english ruler in the case of computing factorialthere is no compelling reason for preferring recursion over direct iteration with loop as more complex example of the use of recursionconsider how to draw the markings of typical english ruler for each inchwe place tick with numeric label we denote the length of the tick designating whole inch as the major tick length between the marks for whole inchesthe ruler contains series of minor ticksplaced at intervals of / inch / inchand so on as the size of the interval decreases by halfthe tick length decreases by one figure demonstrates several such rulers with varying major tick lengths (although not drawn to scale--- -- --- --- --- ( ( (cfigure three sample outputs of an english ruler drawing(aa -inch ruler with major tick length (ba -inch ruler with major tick length (ca -inch ruler with major tick length recursive approach to ruler drawing the english ruler pattern is simple example of fractalthat isa shape that has self-recursive structure at various levels of magnification consider the rule with major tick length shown in figure (bignoring the lines containing and let us consider how to draw the sequence of ticks lying between these lines the central tick (at / inchhas length observe that the two patterns of ticks above and below this central tick are identicaland each has central tick of length |
12,884 | in generalan interval with central tick length > is composed ofan interval with central tick length single tick of length an interval with central tick length although it is possible to draw such ruler using an iterative process (see exercise - )the task is considerably easier to accomplish with recursion our implementation consists of three functionsas shown in code fragment the main functiondraw rulermanages the construction of the entire ruler its arguments specify the total number of inches in the ruler and the major tick length the utility functiondraw linedraws single tick with specified number of dashes (and an optional string labelthat is printed after the tickthe interesting work is done by the recursive draw interval function this function draws the sequence of minor ticks within some intervalbased upon the length of the interval' central tick we rely on the intuition shown at the top of this pageand with base case when that draws nothing for > the first and last steps are performed by recursively calling draw interval( the middle step is performed by calling the function draw line( def draw line(tick lengthtick label) """draw one line with given tick length (followed by optional label""tick length line if tick labeltick label line + print(line def draw interval(center length) """draw tick interval based upon central tick length ""stop when length drops to if center length recursively draw top ticks draw interval(center length draw center tick draw line(center lengthrecursively draw bottom ticks draw interval(center length def draw ruler(num inchesmajor length) """draw english ruler with given number of inchesmajor tick length ""draw inch line draw line(major length for in range( num inches)draw interior ticks for inch draw interval(major length draw inch line and label draw line(major lengthstr( )code fragment recursive implementation of function that draws ruler |
12,885 | illustrating ruler drawing using recursion trace the execution of the recursive draw interval function can be visualized using recursion trace the trace for draw interval is more complicated than in the factorial examplehoweverbecause each instance makes two recursive calls to illustrate thiswe will show the recursion trace in form that is reminiscent of an outline for document see figure output draw interval( draw interval( draw interval( draw interval( draw line( draw interval( draw line( draw interval( draw interval( draw line( draw interval( draw line( draw interval( (previous pattern repeatsfigure partial recursion trace for the call draw interval( the second pattern of calls for draw interval( is not shownbut it is identical to the first |
12,886 | binary search in this sectionwe describe classic recursive algorithmbinary searchthat is used to efficiently locate target value within sorted sequence of elements this is among the most important of computer algorithmsand it is the reason that we so often store data in sorted order (as in figure figure values stored in sorted order within an indexable sequencesuch as python list the numbers at top are the indices when the sequence is unsortedthe standard approach to search for target value is to use loop to examine every elementuntil either finding the target or exhausting the data set this is known as the sequential search algorithm this algorithm runs in (ntime ( linear timesince every element is inspected in the worst case when the sequence is sorted and indexablethere is much more efficient algorithm (for intuitionthink about how you would accomplish this task by hand!for any index jwe know that all the values stored at indices are less than or equal to the value at index jand all the values stored at indices are greater than or equal to that at index this observation allows us to quickly "home inon search target using variant of the children' game "high-low we call an element of the sequence candidate ifat the current stage of the searchwe cannot rule out that this item matches the target the algorithm maintains two parameterslow and highsuch that all the candidate entries have index at least low and at most high initiallylow and high we then compare the target value to the median candidatethat isthe item data[midwith index mid (low high)/ we consider three casesif the target equals data[mid]then we have found the item we are looking forand the search terminates successfully if target data[mid]then we recur on the first half of the sequencethat ison the interval of indices from low to mid if target data[mid]then we recur on the second half of the sequencethat ison the interval of indices from mid to high an unsuccessful search occurs if low highas the interval [lowhighis empty |
12,887 | this algorithm is known as binary search we give python implementation in code fragment and an illustration of the execution of the algorithm in figure whereas sequential search runs in (ntimethe more efficient binary search runs in (log ntime this is significant improvementgiven that if is one billionlog is only (we defer our formal analysis of binary search' running time to proposition in section def binary search(datatargetlowhigh) """return true if target is found in indicated portion of python list the search only considers the portion from data[lowto data[highinclusive "" if low high return false interval is emptyno match else mid (low high/ if target =data[mid]found match return true elif target data[mid] recur on the portion left of the middle return binary search(datatargetlowmid else recur on the portion right of the middle return binary search(datatargetmid highcode fragment an implementation of the binary search algorithm low mid high low mid high low mid high low=mid=high figure example of binary search for target value |
12,888 | file systems modern operating systems define file-system directories (which are also sometimes called "folders"in recursive way namelya file system consists of top-level directoryand the contents of this directory consists of files and other directorieswhich in turn can contain files and other directoriesand so on the operating system allows directories to be nested arbitrarily deep (as long as there is enough space in memory)although there must necessarily be some base directories that contain only filesnot further subdirectories representation of portion of such file system is given in figure /user/rt/coursescs cs grades homeworkshw hw hw programspr pr projectspr papersbuylow sellhigh grades demosmarket figure portion of file system demonstrating nested organization given the recursive nature of the file-system representationit should not come as surprise that many common behaviors of an operating systemsuch as copying directory or deleting directoryare implemented with recursive algorithms in this sectionwe consider one such algorithmcomputing the total disk usage for all files and directories nested within particular directory for illustrationfigure portrays the disk space being used by all entries in our sample file system we differentiate between the immediate disk space used by each entry and the cumulative disk space used by that entry and all nested features for examplethe cs directory uses only of immediate spacebut total of of cumulative space |
12,889 | /user/rt/courses cs cs grades homeworks programs projects hw hw hw pr pr pr grades papers demos buylow sellhigh market figure the same portion of file system given in figure but with additional annotations to describe the amount of disk space that is used within the icon for each file or directory is the amount of space directly used by that artifact above the icon for each directory is an indication of the cumulative disk space used by that directory and all its (recursivecontents the cumulative disk space for an entry can be computed with simple recursive algorithm it is equal to the immediate disk space used by the entry plus the sum of the cumulative disk space usage of any entries that are stored directly within the entry for examplethe cumulative disk space for cs is because it uses itself cumulatively in grades cumulatively in homeworksand cumulatively in programs pseudo-code for this algorithm is given in code fragment algorithm diskusage(path)inputa string designating path to file-system entry outputthe cumulative disk space used by that entry and any nested entries total size(path{immediate disk space used by the entryif path represents directory then for each child entry stored within directory path do total total diskusage(child{recursive callreturn total code fragment an algorithm for computing the cumulative disk space usage nested at file-system entry function size returns the immediate disk space of an entry |
12,890 | python' os module to provide python implementation of recursive algorithm for computing disk usagewe rely on python' os modulewhich provides robust tools for interacting with the operating system during the execution of program this is an extensive librarybut we will only need the following four functionsos path getsize(pathreturn the immediate disk usage (measured in bytesfor the file or directory that is identified by the string path ( /user/rt/coursesos path isdir(pathreturn true if entry designated by string path is directoryfalse otherwise os listdir(pathreturn list of strings that are the names of all entries within directory designated by string path in our sample file systemif the parameter is /user/rt/coursesthis returns the list cs cs os path join(pathfilenamecompose the path string and filename string using an appropriate operating system separator between the two ( the character for unix/linux systemand the character for windowsreturn the string that represents the full path to the file python implementation with use of the os modulewe now convert the algorithm from code fragment into the python implementation of code fragment import os def disk usage(path) """return the number of bytes used by file/folder and any descendents "" total os path getsize(pathaccount for direct usage if os path isdir(path)if this is directory for filename in os listdir(path)then for each child childpath os path join(pathfilenamecompose full path to child add child' usage to total total +disk usage(childpath descriptive output (optional print { :< format(total)path return total return the grand total code fragment recursive function for reporting disk usage of file system |
12,891 | recursion trace to produce different form of recursion tracewe have included an extraneous print statement within our python implementation (line of code fragment the precise format of that output intentionally mirrors output that is produced by classic unix/linux utility named du (for "disk usage"it reports the amount of disk space used by directory and all contents nested withinand can produce verbose reportas given in figure our implementation of the disk usage function produces an identical resultwhen executed on the sample file system portrayed in figure during the execution of the algorithmexactly one recursive call is made for each entry in the portion of the file system that is considered because the print statement is made just before returning from recursive callthe output shown in figure reflects the order in which the recursive calls are completed in particularwe begin and end recursive call for each entry that is nested below another entrycomputing the nested cumulative disk space before we can compute and report the cumulative disk space for the containing entry for examplewe do not know the cumulative total for entry /user/rt/courses/cs until after the recursive calls regarding contained entries gradeshomeworksand programs complete /user/rt/courses/cs /grades /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks/hw /user/rt/courses/cs /homeworks /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs/pr /user/rt/courses/cs /programs /user/rt/courses/cs /user/rt/courses/cs /projects/papers/buylow /user/rt/courses/cs /projects/papers/sellhigh /user/rt/courses/cs /projects/papers /user/rt/courses/cs /projects/demos/market /user/rt/courses/cs /projects/demos /user/rt/courses/cs /projects /user/rt/courses/cs /grades /user/rt/courses/cs /user/rt/coursesfigure report of the disk usage for the file system shown in figure as generated by the unix/linux utility du (with command-line options -ak)or equivalently by our disk usage function from code fragment |
12,892 | analyzing recursive algorithms in we introduced mathematical techniques for analyzing the efficiency of an algorithmbased upon an estimate of the number of primitive operations that are executed by the algorithm we use notations such as big-oh to summarize the relationship between the number of operations and the input size for problem in this sectionwe demonstrate how to perform this type of running-time analysis to recursive algorithms with recursive algorithmwe will account for each operation that is performed based upon the particular activation of the function that manages the flow of control at the time it is executed stated another wayfor each invocation of the functionwe only account for the number of operations that are performed within the body of that activation we can then account for the overall number of operations that are executed as part of the recursive algorithm by taking the sumover all activationsof the number of operations that take place during each individual activation (as an asidethis is also the way we analyze nonrecursive function that calls other functions from within its body to demonstrate this style of analysiswe revisit the four recursive algorithms presented in sections through factorial computationdrawing an english rulerbinary searchand computation of the cumulative size of file system in generalwe may rely on the intuition afforded by recursion trace in recognizing how many recursive activations occurand how the parameterization of each activation can be used to estimate the number of primitive operations that occur within the body of that activation howevereach of these recursive algorithms has unique structure and form computing factorials it is relatively easy to analyze the efficiency of our function for computing factorialsas described in section sample recursion trace for our factorial function was given in figure to compute factorial( )we see that there are total of activationsas the parameter decreases from in the first callto in the second calland so onuntil reaching the base case with parameter it is also cleargiven an examination of the function body in code fragment that each individual activation of factorial executes constant number of operations thereforewe conclude that the overall number of operations for computing factorial(nis ( )as there are activationseach of which accounts for ( operations |
12,893 | drawing an english ruler in analyzing the english ruler application from section we consider the fundamental question of how many total lines of output are generated by an initial call to draw interval( )where denotes the center length this is reasonable benchmark for the overall efficiency of the algorithm as each line of output is based upon call to the draw line utilityand each recursive call to draw interval with nonzero parameter makes exactly one direct call to draw line some intuition may be gained by examining the source code and the recursion trace we know that call to draw interval(cfor spawns two calls to draw interval( - and single call to draw line we will rely on this intuition to prove the following claim proposition for > call to draw interval(cresults in precisely lines of output justificationwe provide formal proof of this claim by induction (see section in factinduction is natural mathematical technique for proving the correctness and efficiency of recursive process in the case of the rulerwe note that an application of draw interval( generates no outputand that this serves as base case for our claim more generallythe number of lines printed by draw interval(cis one more than twice the number generated by call to draw interval( - )as one center line is printed between two such recursive calls by inductionwe have that the number of lines is thus ( - this proof is indicative of more mathematically rigorous toolknown as recurrence equation that can be used to analyze the running time of recursive algorithm that technique is discussed in section in the context of recursive sorting algorithms performing binary search considering the running time of the binary search algorithmas presented in section we observe that constant number of primitive operations are executed at each recursive call of method of binary search hencethe running time is proportional to the number of recursive calls performed we will show that at most log recursive calls are made during binary search of sequence having elementsleading to the following claim proposition the binary search algorithm runs in (log ntime for sorted sequence with elements |
12,894 | justificationto prove this claima crucial fact is that with each recursive call the number of candidate entries still to be searched is given by the value high low moreoverthe number of remaining candidates is reduced by at least one half with each recursive call specificallyfrom the definition of midthe number of remaining candidates is either high low low high low <(mid low or high low low high <high (mid high initiallythe number of candidates is nafter the first call in binary searchit is at most / after the second callit is at most / and so on in generalafter the jth call in binary searchthe number of candidate entries remaining is at most / in the worst case (an unsuccessful search)the recursive calls stop when there are no more candidate entries hencethe maximum number of recursive calls performedis the smallest integer such that in other words (recalling that we omit logarithm' base when it is ) log thuswe have log which implies that binary search runs in (log ntime computing disk space usage our final recursive algorithm from section was that for computing the overall disk space usage in specified portion of file system to characterize the "problem sizefor our analysiswe let denote the number of file-system entries in the portion of the file system that is considered (for examplethe file system portrayed in figure has entries to characterize the cumulative time spent for an initial call to the disk usage functionwe must analyze the total number of recursive invocations that are madeas well as the number of operations that are executed within those invocations we begin by showing that there are precisely recursive invocations of the functionin particularone for each entry in the relevant portion of the file system intuitivelythis is because call to disk usage for particular entry of the file system is only made from within the for loop of code fragment when processing the entry for the unique directory that contains eand that entry will only be explored once |
12,895 | recursion to formalize this argumentwe can define the nesting level of each entry such that the entry on which we begin has nesting level entries stored directly within it have nesting level entries stored within those entries have nesting level and so on we can prove by induction that there is exactly one recursive invocation of disk usage upon each entry at nesting level as base casewhen the only recursive invocation made is the initial one as the inductive steponce we know there is exactly one recursive invocation for each entry at nesting level kwe can claim that there is exactly one invocation for each entry at nesting level kmade within the for loop for the entry at level that contains having established that there is one recursive call for each entry of the file systemwe return to the question of the overall computation time for the algorithm it would be great if we could argue that we spend ( time in any single invocation of the functionbut that is not the case while there are constant number of steps reflect in the call to os path getsize to compute the disk usage directly at that entrywhen the entry is directorythe body of the disk usage function includes for loop that iterates over all entries that are contained within that directory in the worst caseit is possible that one entry includes others based on this reasoningwe could conclude that there are (nrecursive callseach of which runs in (ntimeleading to an overall running time that is ( while this upper bound is technically trueit is not tight upper bound remarkablywe can prove the stronger bound that the recursive algorithm for disk usage completes in (ntimethe weaker bound was pessimistic because it assumed worst-case number of entries for each directory while it is possible that some directories contain number of entries proportional to nthey cannot all contain that many to prove the stronger claimwe choose to consider the overall number of iterations of the for loop across all recursive calls we claim there are precisely such iteration of that loop overall we base this claim on the fact that each iteration of that loop makes recursive call to disk usageand yet we have already concluded that there are total of calls to disk usage (including the original callwe therefore conclude that there are (nrecursive callseach of which uses ( time outside the loopand that the overall number of operations due to the loop is (nsumming all of these boundsthe overall number of operations is (nthe argument we have made is more advanced than with the earlier examples of recursion the idea that we can sometimes get tighter bound on series of operations by considering the cumulative effectrather than assuming that each achieves worst case is technique called amortizationwe will see further example of such analysis in section furthermorea file system is an implicit example of data structure known as treeand our disk usage algorithm is really manifestation of more general algorithm known as tree traversal trees will be the focus of and our argument about the (nrunning time of the disk usage algorithm will be generalized for tree traversals in section |
12,896 | recursion run amok although recursion is very powerful toolit can easily be misused in various ways in this sectionwe examine several problems in which poorly implemented recursion causes drastic inefficiencyand we discuss some strategies for recognizing and avoid such pitfalls we begin by revisiting the element uniqueness problemdefined on page of section we can use the following recursive formulation to determine if all elements of sequence are unique as base casewhen the elements are trivially unique for > the elements are unique if and only if the first elements are uniquethe last items are uniqueand the first and last elements are different (as that is the only pair that was not already checked as subcasea recursive implementation based on this idea is given in code fragment named unique (to differentiate it from unique and unique from def unique (sstartstop) """return true if there are no duplicate elements in slice [start:stop"" if stop start < return true at most one item elif not unique(sstartstop- )return false first part has duplicate elif not unique(sstart+ stop)return false second part has duplicate elsereturn [start! [stop- do first and last differcode fragment recursive unique for testing element uniqueness unfortunatelythis is terribly inefficient use of recursion the nonrecursive part of each call uses ( timeso the overall running time will be proportional to the total number of recursive invocations to analyze the problemwe let denote the number of entries under considerationthat islet nstop start if then the running time of unique is ( )since there are no recursive calls for this case in the general casethe important observation is that single call to unique for problem of size may result in two recursive calls on problems of size those two calls with size could in turn result in four calls (two eachwith range of size and thus eight calls with size and so on thusin the worst casethe total number of function calls is given by the geometric summation - which is equal to by proposition thusthe running time of function unique is ( this is an incredibly inefficient function for solving the element uniqueness problem its inefficiency comes not from the fact that it uses recursion--it comes from the fact that it uses recursion poorlywhich is something we address in exercise - |
12,897 | an inefficient recursion for computing fibonacci numbers in section we introduced process for generating the fibonacci numberswhich can be defined recursively as followsf fn fn- fn- for ironicallya direct implementation based on this definition results in the function bad fibonacci shown in code fragment which computes the sequence of fibonacci numbers by making two recursive calls in each non-base case def bad fibonacci( ) """return the nth fibonacci number "" if < return else return bad fibonacci( - bad fibonacci( - code fragment computing the nth fibonacci number using binary recursion unfortunatelysuch direct implementation of the fibonacci formula results in terribly inefficient function computing the nth fibonacci number in this way requires an exponential number of calls to the function specificallylet cn denote the number of calls performed in the execution of bad fibonacci(nthenwe have the following values for the cn 'sc if we follow the pattern forwardwe see that the number of calls more than doubles for each two consecutive indices that isc is more than twice is more than twice is more than twice and so on thuscn / which means that bad fibonacci(nmakes number of calls that is exponential in |
12,898 | an efficient recursion for computing fibonacci numbers we were tempted into using the bad recursion formulation because of the way the nth fibonacci numberfn depends on the two previous valuesfn- and fn- but notice that after computing fn- the call to compute fn- requires its own recursive call to compute fn- as it does not have knowledge of the value of fn- that was computed at the earlier level of recursion that is duplicative work worse yetboth of those calls will need to (re)compute the value of fn- as will the computation of fn- this snowballing effect is what leads to the exponential running time of bad recursion we can compute fn much more efficiently using recursion in which each invocation makes only one recursive call to do sowe need to redefine the expectations of the function rather than having the function return single valuewhich is the nth fibonacci numberwe define recursive function that returns pair of consecutive fibonacci numbers (fn fn- )using the convention - although it seems to be greater burden to report two consecutive fibonacci numbers instead of onepassing this extra information from one level of the recursion to the next makes it much easier to continue the process (it allows us to avoid having to recompute the second value that was already known within the recursion an implementation based on this strategy is given in code fragment def good fibonacci( ) """return pair of fibonacci numbersf(nand ( - "" if < return ( , else (abgood fibonacci( - return ( +bacode fragment computing the nth fibonacci number using linear recursion in terms of efficiencythe difference between the bad recursion and the good recursion for this problem is like night and day the bad fibonacci function uses exponential time we claim that the execution of function good fibonacci(ntakes (ntime each recursive call to good fibonacci decreases the argument by thereforea recursion trace includes series of function calls because the nonrecursive work for each call uses constant timethe overall computation executes in (ntime |
12,899 | maximum recursive depth in python another danger in the misuse of recursion is known as infinite recursion if each recursive call makes another recursive callwithout ever reaching base casethen we have an infinite series of such calls this is fatal error an infinite recursion can quickly swamp computing resourcesnot only due to rapid use of the cpubut because each successive call creates an activation record requiring additional memory blatant example of an ill-formed recursion is the followingdef fib( )return fib(nfib(nequals fib(nhoweverthere are far more subtle errors that can lead to an infinite recursion revisiting our implementation of binary search in code fragment in the final case (line we make recursive call on the right portion of the sequencein particular going from index mid+ to high had that line instead been written as return binary search(datatargetmidhighnote the use of mid this could result in an infinite recursion in particularwhen searching range of two elementsit becomes possible to make recursive call on the identical range programmer should ensure that each recursive call is in some way progressing toward base case (for exampleby having parameter value that decreases with each callhoweverto combat against infinite recursionsthe designers of python made an intentional decision to limit the overall number of function activations that can be simultaneously active the precise value of this limit depends upon the python distributionbut typical default value is if this limit is reachedthe python interpreter raises runtimeerror with messagemaximum recursion depth exceeded for many legitimate applications of recursiona limit of nested function calls suffices for exampleour binary search function (section has (log nrecursive depthand so for the default recursive limit to be reachedthere would need to be elements (farfar more than the estimated number of atoms in the universehoweverin the next section we discuss several algorithms that have recursive depth proportional to python' artificial limit on the recursive depth could disrupt such otherwise legitimate computations fortunatelythe python interpreter can be dynamically reconfigured to change the default recursive limit this is done through use of module named syswhich supports getrecursionlimit function and setrecursionlimit sample usage of those functions is demonstrated as followsimport sys old sys getrecursionlimitsys setrecursionlimit( perhaps is typical change to allow million nested calls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.