id
int64
0
25.6k
text
stringlengths
0
4.59k
21,700
scopes and namespaces when computing sum with the syntax in pythonthe names and must have been previously associated with objects that serve as valuesa nameerror will be raised if no such definitions are found the process of determining the value associated with an identifier is known as name resolution whenever an ide...
21,701
when an identifier is indicated in commandpython searches series of namespaces in the process of name resolution firstthe most locally enclosing scope is searched for given name if not found therethe next outer scope is searchedand so on we will continue our examination of namespacesin section when discussing python' t...
21,702
modules and the import statement we have already introduced many functions ( maxand classes ( listthat are defined within python' built-in namespace depending on the version of pythonthere are approximately - definitions that were deemed significant enough to be included in that built-in namespace beyond the built-in d...
21,703
it is worth noting that top-level commands with the module source code are executed when the module is first importedalmost as if the module were its own script there is special construct for embedding commands within the module that will be executed if the module is directly invoked as scriptbut not when the module is...
21,704
next number in sequence based upon one or more past numbers that it has generated indeeda simple yet popular pseudo-random number generator chooses its next number based solely on the most recently chosen number and some additional parameters using the following formula next ( *current bnwhere aband are appropriately c...
21,705
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - write short python functionis multiple(nm)that takes two integer values and returns true if is multiple of mthat isn mi for some integer iand false otherwise - write short python functionis even( )that takes an integer ...
21,706
creativity - write pseudo-code description of function that reverses list of integersso that the numbers are listed in the opposite order than they were beforeand compare this method to an equivalent python function for doing the same thing - write short python function that takes sequence of integer values and determi...
21,707
- write short python program that takes two arrays and of length storing int valuesand returns the dot product of and that isit returns an array of length such that [ia[ib[ ]for - give an example of python code fragment that attempts to write an element to list based on an index that may be out of bounds if that index ...
21,708
projects - write python program that outputs all possible strings formed by using the characters and exactly once - write python program that can take positive integer greater than as input and write out the number of times one must repeatedly divide this number by before getting value less than - write python program ...
21,709
notes the official python web site (modules the python interpreter is itself useful referenceas the interactive command help(fooprovides documentation for any functionclassor module that foo identifies books providing an introduction to programming in python include titles authored by campbell et al [ ]cedar [ ]dawson ...
21,710
object-oriented programming contents goalsprinciplesand patterns object-oriented design goals object-oriented design principles design patterns software development design pseudo-code coding style and documentation testing and debugging class definitions examplecreditcard class operator overloading and python' special ...
21,711
goalsprinciplesand patterns as the name impliesthe main "actorsin the object-oriented paradigm are called objects each object is an instance of class each class presents to the outside world concise and consistent view of the objects that are instances of this classwithout going into too much unnecessary detail or givi...
21,712
adaptability modern software applicationssuch as web browsers and internet search enginestypically involve large programs that are used for many years softwarethereforeneeds to be able to evolve over time in response to changing conditions in its environment thusanother important goal of quality software is that it ach...
21,713
modularity modern software systems typically consist of several different components that must interact correctly in order for the entire system to work properly keeping these interactions straight requires that these different components be well organized modularity refers to an organizing principle in which different...
21,714
as programming languagepython provides great deal of latitude in regard to the specification of an interface python has tradition of treating abstractions implicitly using mechanism known as duck typing as an interpreted and dynamically typed languagethere is no "compile timechecking of data types in pythonand no forma...
21,715
design patterns object-oriented design facilitates reusablerobustand adaptable software designing good code takes more than simply understanding object-oriented methodologieshowever it requires the effective use of object-oriented design techniques computing researchers and practitioners have developed variety of organ...
21,716
software development traditional software development involves several phases three major steps are design implementation testing and debugging in this sectionwe briefly discuss the role of these phasesand we introduce several good practices for programming in pythonincluding coding stylenaming conventionsformal docume...
21,717
common tool for developing an initial high-level design for project is the use of crc cards class-responsibility-collaborator (crccards are simple index cards that subdivide the work required of program the main idea behind this tool is to have each card represent componentwhich will ultimately become class in the prog...
21,718
pseudo-code as an intermediate step before the implementation of designprogrammers are often asked to describe algorithms in way that is intended for human eyes only such descriptions are called pseudo-code pseudo-code is not computer programbut is more structured than usual prose it is mixture of natural language and ...
21,719
use meaningful names for identifiers try to choose names that can be read aloudand choose names that reflect the actionresponsibilityor data each identifier is naming classes (other than python' built-in classesshould have name that serves as singular nounand should be capitalized ( date rather than date or dateswhen m...
21,720
documentation python provides integrated support for embedding formal documentation directly in source code using mechanism known as docstring formallyany string literal that appears as the first statement within the body of moduleclassor function (including member function of classwill be considered to be docstring by...
21,721
testing and debugging testing is the process of experimentally checking the correctness of programwhile debugging is the process of tracking the execution of program and discovering the errors in it testing and debugging are often the most time-consuming activity in the development of program testing careful testing pl...
21,722
bottom-up testing proceeds from lower-level components to higher-level components for examplebottom-level functionswhich do not invoke other functionsare tested firstfollowed by functions that call only bottom-level functionsand so on similarly class that does not depend upon any other classes can be tested before anot...
21,723
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...
21,724
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...
21,725
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 ...
21,726
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 ...
21,727
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...
21,728
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...
21,729
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...
21,730
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...
21,731
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 ...
21,732
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[ ...
21,733
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...
21,734
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...
21,735
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...
21,736
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...
21,737
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 ...
21,738
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...
21,739
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...
21,740
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...
21,741
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...
21,742
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 ...
21,743
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...
21,744
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...
21,745
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...
21,746
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...
21,747
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...
21,748
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...
21,749
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...
21,750
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...
21,751
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...
21,752
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...
21,753
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...
21,754
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 ...
21,755
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...
21,756
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...
21,757
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 ...
21,758
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...
21,759
- 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...
21,760
- 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...
21,761
- 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...
21,762
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 ...
21,763
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...
21,764
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...
21,765
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...
21,766
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...
21,767
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...
21,768
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...
21,769
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...
21,770
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...
21,771
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...
21,772
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...
21,773
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...
21,774
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...
21,775
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...
21,776
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...
21,777
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...
21,778
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...
21,779
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...
21,780
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...
21,781
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...
21,782
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 ...
21,783
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...
21,784
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...
21,785
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...
21,786
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...
21,787
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...
21,788
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 ...
21,789
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...
21,790
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...
21,791
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...
21,792
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 ...
21,793
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...
21,794
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 ...
21,795
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...
21,796
- 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 ...
21,797
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...
21,798
- 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...
21,799
- 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...