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...
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 (mea...
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 ...
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 ...
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...
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...
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 ( )altern...
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-de...
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 ...
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[ ...
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 t...
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 element...
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 effe...
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 math...
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 ...
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...
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...
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...
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 ad...
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 ...
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 arithmet...
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 ra...
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 (firstfictitiou...
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 basegeometricprogressionprin...
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 ba...
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...
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 supp...
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 na...
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 names...
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 se...
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 def...
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 ...
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...
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 th...
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 ...
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 v...
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 i...
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 quick...
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 h...
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 ...
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 in...
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 bat...
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 fractio...
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 valua...
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 w...
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 ana...
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...
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 c...
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 seq...
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 operati...
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 ju...
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 us...
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 p...
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...
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 tha...
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 c...
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 large...
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 desig...
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...
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 ...
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 fix...
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 wit...
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 initializ...
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 zer...
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 thi...
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 ...
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 presen...
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...
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 s...
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 ...
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 c...
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 ...
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 algorithm...
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 ...
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 p...
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 i...
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 integer...
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" - c...
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 o...
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 elimin...
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 execut...
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 formall...
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 e...
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 o...
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 implement...
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 ...
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 i...
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 d...
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 ...
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 spac...
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 getsiz...
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...
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...
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 lin...
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 rema...
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 in...
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 unique...
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...
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 doe...
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 on...