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 identifier is assigned to valuethat definition is made with specific scope top-level assignments are typically made in what is known as global scope assignments made within the body of function typically have scope that is local to that function call thereforean assignmentx within function has no effect on the identifierxin the broader scope each distinct scope in python is represented using an abstraction known as namespace namespace manages all identifiers that are currently defined in given scope figure portrays two namespacesone being that of caller to our count function from section and the other being the local namespace during the execution of that function str float gpa grades str major list target data int item cs str str str abafigure portrayal of the two namespaces associated with user' call count(gradesa )as defined in section the left namespace is the caller' and the right namespace represents the local scope of the function python implements namespace with its own dictionary that maps each identifying string ( to its associated value python provides several ways to examine given namespace the functiondirreports the names of the identifiers in given namespace ( the keys of the dictionary)while the functionvarsreturns the full dictionary by defaultcalls to dirand varsreport on the most locally enclosing namespace in which they are executed |
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' treatment of object-orientation we will see that each object has its own namespace to store its attributesand that classes each have namespace as well first-class objects in the terminology of programming languagesfirst-class objects are instances of type that can be assigned to an identifierpassed as parameteror returned by function all of the data types we introduced in section such as int and listare clearly first-class types in python in pythonfunctions and classes are also treated as first-class objects for examplewe could write the followingscream print screamhello assign name 'screamto the function denoted as 'printcall that function in this casewe have not created new functionwe have simply defined scream as an alias for the existing print function while there is little motivation for precisely this exampleit demonstrates the mechanism that is used by python to allow one function to be passed as parameter to another on page we noted that the built-in functionmaxaccepts an optional keyword parameter to specify non-default order when computing maximum for examplea caller can use the syntaxmax(abkey=abs)to determine which value has the larger absolute value within the body of that functionthe formal parameterkeyis an identifier that will be assigned to the actual parameterabs in terms of namespacesan assignment such as scream printintroduces the identifierscreaminto the current namespacewith its value being the object that represents the built-in functionprint the same mechanism is applied when userdefined function is declared for exampleour count function from section beings with the following syntaxdef count(datatarget)such declaration introduces the identifiercountinto the current namespacewith the value being function instance representing its implementation in similar fashionthe name of newly defined class is associated with representation of that class as its value (class definitions will be introduced in the next |
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 definitionsthe standard python distribution includes perhaps tens of thousands of other valuesfunctionsand classes that are organized in additional librariesknown as modulesthat can be imported from within program as an examplewe consider the math module while the built-in namespace includes few mathematical functions ( absminmaxround)many more are relegated to the math module ( sincossqrtthat module also defines approximate values for the mathematical constantspi and python' import statement loads definitions from module into the current namespace one form of an import statement uses syntax such as the followingfrom math import pisqrt this command adds both pi and sqrtas defined in the math moduleinto the current namespaceallowing direct use of the identifierpior call of the functionsqrt( if there are many definitions from the same module to be importedan asterisk may be used as wild cardas infrom math import but this form should be used sparingly the danger is that some of the names defined in the module may conflict with names already in the current namespace (or being imported from another module)and the import causes the new definitions to replace existing ones another approach that can be used to access many definitions from the same module is to import the module itselfusing syntax such asimport math formallythis adds the identifiermathto the current namespacewith the module as its value (modules are also first-class objects in python once importedindividual definitions from the module can be accessed using fully-qualified namesuch as math pi or math sqrt( creating new module to create new moduleone simply has to put the relevant definitions in file named with py suffix those definitions can be imported from any other py file within the same project directory for exampleif we were to put the definition of our count function (see section into file named utility pywe could import that function using the syntaxfrom utility import count |
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 imported from another script such commands should be placed in body of conditional statement of the following formif name =__main__ using our hypothetical utility py module as an examplesuch commands will be executed if the interpreter is started with command python utility pybut not when the utility module is imported into another context this approach is often used to embed what are known as unit tests within the modulewe will discuss unit testing further in section existing modules table provides summary of few available modules that are relevant to study of data structures we have already discussed the math module briefly in the remainder of this sectionwe highlight another module that is particularly important for some of the data structures and algorithms that we will study later in this book existing modules module name array collections copy heapq math os random re sys time description provides compact array storage for primitive types defines additional data structures and abstract base classes involving collections of objects defines general functions for making copies of objects provides heap-based priority queue functions (see section defines common mathematical constants and functions provides support for interactions with the operating system provides random number generation provides support for processing regular expressions provides additional level of interaction with the python interpreter provides support for measuring timeor delaying program table some existing python modules relevant to data structures and algorithms pseudo-random number generation python' random module provides the ability to generate pseudo-random numbersthat isnumbers that are statistically random (but not necessarily truly randoma pseudo-random number generator uses deterministic formula to generate the |
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 chosen integers python uses more advanced technique known as mersenne twister it turns out that the sequences generated by these techniques can be proven to be statistically uniformwhich is usually good enough for most applications requiring random numberssuch as games for applicationssuch as computer security settingswhere one needs unpredictable random sequencesthis kind of formula should not be used insteadone should ideally sample from source that is actually randomsuch as radio static coming from outer space since the next number in pseudo-random generator is determined by the previous number( )such generator always needs place to startwhich is called its seed the sequence of numbers generated for given seed will always be the same one common trick to get different sequence each time program is run is to use seed that will be different for each run for examplewe could use some timed input from user or the current system time in milliseconds python' random module provides support for pseudo-random number generation by defining random classinstances of that class serve as generators with independent state this allows different aspects of program to rely on their own pseudo-random number generatorso that calls to one generator do not affect the sequence of numbers produced by another for convenienceall of the methods supported by the random class are also supported as stand-alone functions of the random module (essentially using single generator instance for all top-level callssyntax seed(hashablerandomrandint( ,brandrange(startstopstepchoice(seqshuffle(seqdescription initializes the pseudo-random number generator based upon the hash value of the parameter returns pseudo-random floating-point value in the interval [ returns pseudo-random integer in the closed interval [abreturns pseudo-random integer in the standard python range indicated by the parameters returns an element of the given sequence chosen pseudo-randomly reorders the elements of the given sequence pseudo-randomly table methods supported by instances of the random classand as top-level functions of the random module |
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 value and returns true if is evenand false otherwise howeveryour function cannot use the multiplicationmoduloor division operators - write short python functionminmax(data)that takes sequence of one or more numbersand returns the smallest and largest numbersin the form of tuple of length two do not use the built-in functions min or max in implementing your solution - write short python function that takes positive integer and returns the sum of the squares of all the positive integers smaller than - give single command that computes the sum from exercise - relying on python' comprehension syntax and the built-in sum function - write short python function that takes positive integer and returns the sum of the squares of all the odd positive integers smaller than - give single command that computes the sum from exercise - relying on python' comprehension syntax and the built-in sum function - python allows negative integers to be used as indices into sequencesuch as string if string has length nand expression [kis used for index - such that [jreferences the same elementr- what parameters should be sent to the range constructorto produce range with values - what parameters should be sent to the range constructorto produce range with values - - - - - demonstrate how to use python' list comprehension syntax to produce the list [ - python' random module includes function choice(datathat returns random element from non-empty sequence the random module includes more basic function randrangewith parameterization similar to the built-in range functionthat return random choice from the given range using only the randrange functionimplement your own version of the choice function |
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 determines if there is distinct pair of numbers in the sequence whose product is odd - write python function that takes sequence of numbers and determines if all the numbers are different from each other (that isthey are distinctc- in our implementation of the scale function (page )the body of the loop executes the command data[jfactor we have discussed that numeric types are immutableand that use of the operator in this context causes the creation of new instance (not the mutation of an existing instancehow is it still possiblethenthat our implementation of scale changes the actual parameter sent by the callerc- had we implemented the scale function (page as followsdoes it work properlydef scale(datafactor)for val in dataval factor explain why or why not - demonstrate how to use python' list comprehension syntax to produce the list [ - demonstrate how to use python' list comprehension syntax to produce the list ]but without having to type all such characters literally - python' random module includes function shuffle(datathat accepts list of elements and randomly reorders the elements so that each possible order occurs with equal probability the random module includes more basic function randint(abthat returns uniformly random integer from to (including both endpointsusing only the randint functionimplement your own version of the shuffle function - write python program that repeatedly reads lines from standard input until an eoferror is raisedand then outputs those lines in reverse order ( user can indicate end of input by typing ctrl- |
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 is out of boundsthe program should catch the exception that resultsand print the following error message"don' try buffer overflow attacks in python! - write short python function that counts the number of vowels in given character string - write short python function that takes string srepresenting sentenceand returns copy of the string with all punctuation removed for exampleif given the string "let trymike "this function would return "lets try mikec- write short program that takes as input three integersaband cfrom the console and determines if they can be used in correct arithmetic formula (in the given order)like " ," ,or " - in section we provided three different implementations of generator that computes factors of given integer the third of those implementationsfrom page was the most efficientbut we noted that it did not yield the factors in increasing order modify the generator so that it reports factors in increasing orderwhile maintaining its general performance advantages - the -norm of vector ( vn in -dimensional space is defined as vv vnp for the special case of this results in the traditional euclidean normwhich represents the length of the vector for examplethe euclidean norm of two-dimensional with coordinates ( has vector euclidean norm of give an implementation of function named norm such that norm(vpreturns the -norm value of and norm(vreturns the euclidean norm of you may assume that is list of numbers |
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 that can "make change your program should take two numbers as inputone that is monetary amount charged and the other that is monetary amount given it should then return the number of each kind of bill and coin to give back as change for the difference between the amount given and the amount charged the values assigned to the bills and coins can be based on the monetary system of any current or former government try to design your program so that it returns as few bills and coins as possible - write python program that can simulate simple calculatorusing the console as the exclusive input and output device that iseach input to the calculatorbe it numberlike or or an operatorlike or =can be done on separate line after each such inputyou should output to the python console what would be displayed on your calculator - write python program that simulates handheld calculator your program should process input from the python console representing buttons that are "pushed,and then output the contents of the screen after each operation is performed minimallyyour calculator should be able to process the basic arithmetic operations and reset/clear operation - common punishment for school children is to write out sentence multiple times write python stand-alone program that will write out the following sentence one hundred times" will never spam my friends again your program should number each of the sentences and it should make eight different random-looking typos - the birthday paradox says that the probability that two people in room will have the same birthday is more than halfprovided nthe number of people in the roomis more than this property is not really paradoxbut many people find it surprising design python program that can test this paradox by series of experiments on randomly generated birthdayswhich test this paradox for - write python program that inputs list of wordsseparated by whitespaceand outputs how many times each word appears in the list you need not worry about efficiency at this pointhoweveras this topic is something that will be addressed later in this book |
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 [ ]goldwasser and letscher [ ]lutz [ ]perkovic [ ]and zelle [ more complete reference books on python include titles by beazley [ ]and summerfield [ |
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 methods examplemultidimensional vector class iterators examplerange class inheritance extending the creditcard class hierarchy of numeric progressions abstract base classes namespaces and object-orientation instance and class namespaces name resolution and dynamic dispatch shallow and deep copying exercises |
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 giving others access to the inner workings of the objects the class definition typically specifies instance variablesalso known as data membersthat the object containsas well as the methodsalso known as member functionsthat the object can execute this view of computing is intended to fulfill several goals and incorporate several design principleswhich we discuss in this object-oriented design goals software implementations should achieve robustnessadaptabilityand reusability (see figure robustness adaptability reusability figure goals of object-oriented design robustness every good programmer wants to develop software that is correctwhich means that program produces the right output for all the anticipated inputs in the program' application in additionwe want software to be robustthat iscapable of handling unexpected inputs that are not explicitly defined for its application for exampleif program is expecting positive integer (perhaps representing the price of an itemand instead is given negative integerthen the program should be able to recover gracefully from this error more importantlyin life-critical applicationswhere software error can lead to injury or loss of lifesoftware that is not robust could be deadly this point was driven home in the late in accidents involving therac- radiation-therapy machinewhich severely overdosed six patients between and some of whom died from complications resulting from their radiation overdose all six accidents were traced to software errors |
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 achieves adaptability (also called evolvabilityrelated to this concept is portabilitywhich is the ability of software to run with minimal change on different hardware and operating system platforms an advantage of writing software in python is the portability provided by the language itself reusability going hand in hand with adaptability is the desire that software be reusablethat isthe same code should be usable as component of different systems in various applications developing quality software can be an expensive enterpriseand its cost can be offset somewhat if the software is designed in way that makes it easily reusable in future applications such reuse should be done with carehoweverfor one of the major sources of software errors in the therac- came from inappropriate reuse of therac- software (which was not object-oriented and not designed for the hardware platform used with the therac- object-oriented design principles chief among the principles of the object-oriented approachwhich are intended to facilitate the goals outlined aboveare the following (see figure )modularity abstraction encapsulation modularity abstraction encapsulation figure principles of object-oriented design |
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 components of software system are divided into separate functional units as real-world analogya house or apartment can be viewed as consisting of several interacting unitselectricalheating and coolingplumbingand structural rather than viewing these systems as one giant jumble of wiresventspipesand boardsthe organized architect designing house or apartment will view them as separate modules that interact in well-defined ways in so doinghe or she is using modularity to bring clarity of thought that provides natural way of organizing functions into distinct manageable units in like mannerusing modularity in software system can also provide powerful organizing framework that brings clarity to an implementation in pythonwe have already seen that module is collection of closely related functions and classes that are defined together in single file of source code python' standard libraries includefor examplethe math modulewhich provides definitions for key mathematical constants and functionsand the os modulewhich provides support for interacting with the operating system the use of modularity helps support the goals listed in section robustness is greatly increased because it is easier to test and debug separate components before they are integrated into larger software system furthermorebugs that persist in complete system might be traced to particular componentwhich can be fixed in relative isolation the structure imposed by modularity also helps enable software reusability if software modules are written in general waythe modules can be reused when related need arises in other contexts this is particularly relevant in study of data structureswhich can typically be designed with sufficient abstraction and generality to be reused in many applications abstraction the notion of abstraction is to distill complicated system down to its most fundamental parts typicallydescribing the parts of system involves naming them and explaining their functionality applying the abstraction paradigm to the design of data structures gives rise to abstract data types (adtsan adt is mathematical model of data structure that specifies the type of data storedthe operations supported on themand the types of parameters of the operations an adt specifies what each operation doesbut not how it does it we will typically refer to the collective set of behaviors supported by an adt as its public interface |
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 formal requirement for declarations of abstract base classes instead programmers assume that an object supports set of known behaviorswith the interpreter raising run-time error if those assumptions fail the description of this as "duck typingcomes from an adage attributed to poet james whitcomb rileystating that "when see bird that walks like duck and swims like duck and quacks like ducki call that bird duck more formallypython supports abstract data types using mechanism known as an abstract base class (abcan abstract base class cannot be instantiated ( you cannot directly create an instance of that class)but it defines one or more common methods that all implementations of the abstraction must have an abc is realized by one or more concrete classes that inherit from the abstract base class while providing implementations for those method declared by the abc python' abc module provides formal support for abcsalthough we omit such declarations for simplicity we will make use of several existing abstract base classes coming from python' collections modulewhich includes definitions for several common data structure adtsand concrete implementations of some of those abstractions encapsulation another important principle of object-oriented design is encapsulation different components of software system should not reveal the internal details of their respective implementations one of the main advantages of encapsulation is that it gives one programmer freedom to implement the details of componentwithout concern that other programmers will be writing code that intricately depends on those internal decisions the only constraint on the programmer of component is to maintain the public interface for the componentas other programmers will be writing code that depends on that interface encapsulation yields robustness and adaptabilityfor it allows the implementation details of parts of program to change without adversely affecting other partsthereby making it easier to fix bugs or add new functionality with relatively local changes to component throughout this bookwe will adhere to the principle of encapsulationmaking clear which aspects of data structure are assumed to be public and which are assumed to be internal details with that saidpython provides only loose support for encapsulation by conventionnames of members of class (both data members and member functionsthat start with single underscore character ( secretare assumed to be nonpublic and should not be relied upon those conventions are reinforced by the intentional omission of those members from automatically generated documentation |
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 organizational concepts and methodologies for designing quality object-oriented software that is concisecorrectand reusable of special relevance to this book is the concept of design patternwhich describes solution to "typicalsoftware design problem pattern provides general template for solution that can be applied in many different situations it describes the main elements of solution in an abstract way that can be specialized for specific problem at hand it consists of namewhich identifies the patterna contextwhich describes the scenarios for which this pattern can be applieda templatewhich describes how the pattern is appliedand resultwhich describes and analyzes what the pattern produces we present several design patterns in this bookand we show how they can be consistently applied to implementations of data structures and algorithms these design patterns fall into two groups--patterns for solving algorithm design problems and patterns for solving software engineering problems the algorithm design patterns we discuss include the followingrecursion (amortization (sections and divide-and-conquer (section prune-and-searchalso known as decrease-and-conquer (section brute force (section dynamic programming (section the greedy method (sections and likewisethe software engineering design patterns we discuss includeiterator (sections and adapter (section position (sections and composition (sections and template method (sections and locator (section factory method (section rather than explain each of these concepts herehoweverwe introduce them throughout the text as noted above for each patternbe it for algorithm engineering or software engineeringwe explain its general use and we illustrate it with at least one concrete example |
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 documentationand unit testing design for object-oriented programmingthe design step is perhaps the most important phase in the process of developing software for it is in the design step that we decide how to divide the workings of our program into classeswe decide how these classes will interactwhat data each will storeand what actions each will perform indeedone of the main challenges that beginning programmers face is deciding what classes to define to do the work of their program while general prescriptions are hard to come bythere are some rules of thumb that we can apply when determining how to design our classesresponsibilitiesdivide the work into different actorseach with different responsibility try to describe responsibilities using action verbs these actors will form the classes for the program independencedefine the work for each class to be as independent from other classes as possible subdivide responsibilities between classes so that each class has autonomy over some aspect of the program give data (as instance variablesto the class that has jurisdiction over the actions that require access to this data behaviorsdefine the behaviors for each class carefully and preciselyso that the consequences of each action performed by class will be well understood by other classes that interact with it these behaviors will define the methods that this class performsand the set of behaviors for class are the interface to the classas these form the means for other pieces of code to interact with objects from the class defining the classestogether with their instance variables and methodsare key to the design of an object-oriented program good programmer will naturally develop greater skill in performing these tasks over timeas experience teaches him or her to notice patterns in the requirements of program that match patterns that he or she has seen before |
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 program we write the name of each component on the top of an index card on the left-hand side of the cardwe begin writing the responsibilities for this component on the right-hand sidewe list the collaborators for this componentthat isthe other components that this component will have to interact with to perform its duties the design process iterates through an action/actor cyclewhere we first identify an action (that isa responsibility)and we then determine an actor (that isa componentthat is best suited to perform that action the design is complete when we have assigned all actions to actors in using index cards for this process (rather than larger pieces of paper)we are relying on the fact that each component should have small set of responsibilities and collaborators enforcing this rule helps keep the individual classes manageable as the design takes forma standard approach to explain and document the design is the use of uml (unified modeling languagediagrams to express the organization of program uml diagrams are standard visual notation to express object-oriented software designs several computer-aided tools are available to build uml diagrams one type of uml figure is known as class diagram an example of such diagram is given in figure for class that represents consumer credit card the diagram has three portionswith the first designating the name of the classthe second designating the recommended instance variablesand the third designating the recommended methods of the class in section we discuss our naming conventionsand in section we provide complete implementation of python creditcard class based on this design creditcard classfieldscustomer bank account balance limit behaviorsget customerget bankget accountmake payment(amountget balanceget limitcharge(pricefigure class diagram for proposed creditcard class |
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 high-level programming constructs that describe the main ideas behind generic implementation of data structure or algorithm because pseudo-code is designed for human readernot computerwe can communicate high-level ideaswithout being burdened with low-level implementation details at the same timewe should not gloss over important steps like many forms of human communicationfinding the right balance is an important skill that is refined through practice in this bookwe rely on pseudo-code style that we hope will be evident to python programmersyet with mix of mathematical notations and english prose for examplewe might use the phrase "indicate an errorrather than formal raise statement following conventions of pythonwe rely on indentation to indicate the extent of control structures and on an indexing notation in which entries of sequence with length are indexed from [ to [ howeverwe choose to enclose comments within curly braces like these in our pseudo-coderather than using python' character coding style and documentation programs should be made easy to read and understand good programmers should therefore be mindful of their coding styleand develop style that communicates the important aspects of program' design for both humans and computers conventions for coding style tend to vary between different programming communities the official style guide for python code is available online at the main principles that we adopt are as followspython code blocks are typically indented by spaces howeverto avoid having our code fragments overrun the book' marginswe use spaces for each level of indentation it is strongly recommended that tabs be avoidedas tabs are displayed with differing widths across systemsand tabs and spaces are not viewed as identical by the python interpreter many python-aware editors will automatically replace tabs with an appropriate number of spaces |
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 multiple words are concatenated to form class namethey should follow the so-called "camelcaseconvention in which the first letter of each word is capitalized ( creditcardfunctionsincluding member functions of classshould be lowercase if multiple words are combinedthey should be separated by underscores ( make paymentthe name of function should typically be verb that describes its affect howeverif the only purpose of the function is to return valuethe function name may be noun that describes the value ( sqrt rather than calculate sqrtnames that identify an individual object ( parameterinstance variableor local variableshould be lowercase noun ( priceoccasionallywe stray from this rule when using single uppercase letter to designate the name of data structures (such as tree tidentifiers that represent value considered to be constant are traditionally identified using all capital letters and with underscores to separate words ( max sizerecall from our discussion of encapsulation that identifiers in any context that begin with single leading underscore ( secretare intended to suggest that they are only for "internaluse to class or moduleand not part of public interface use comments that add meaning to program and explain ambiguous or confusing constructs in-line comments are good for quick explanationsthey are indicated in python following the characteras in if = is odd multiline block comments are good for explaining more complex code sections in pythonthese are technically multiline string literalstypically delimited with triple quotes (""")which have no effect when executed in the next sectionwe discuss the use of block comments for documentation |
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 conventionthose string literals should be delimited within triple quotes ("""as an exampleour version of the scale function from page could be documented as followsdef scale(datafactor)"""multiply all entries of numeric data list by the given factor ""for in range(len(data))data[jfactor it is common to use the triple-quoted string delimiter for docstringeven when the string fits on single lineas in the above example more detailed docstrings should begin with single line that summarizes the purposefollowed by blank lineand then further details for examplewe might more clearly document the scale function as followsdef scale(datafactor)"""multiply all entries of numeric data list by the given factor data an instance of any mutable sequence type (such as listcontaining numeric elements factor number that serves as the multiplicative factor for scaling ""for in range(len(data))data[jfactor docstring is stored as field of the modulefunctionor class in which it is declared it serves as documentation and can be retrieved in variety of ways for examplethe command help( )within the python interpreterproduces the documentation associated with the identified object an external tool named pydoc is distributed with python and can be used to generate formal documentation as text or as web page guidelines for authoring useful docstrings are available atin this bookwe will try to present docstrings when space allows omitted docstrings can be found in the online version of our source code |
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 plan is an essential part of writing program while verifying the correctness of program over all possible inputs is usually infeasiblewe should aim at executing the program on representative subset of inputs at the very minimumwe should make sure that every method of class is tested at least once (method coverageeven bettereach code statement in the program should be executed at least once (statement coverageprograms often tend to fail on special cases of the input such cases need to be carefully identified and tested for examplewhen testing method that sorts (that isputs in ordera sequence of integerswe should consider the following inputsthe sequence has zero length (no elementsthe sequence has one element all the elements of the sequence are the same the sequence is already sorted the sequence is reverse sorted in addition to special inputs to the programwe should also consider special conditions for the structures used by the program for exampleif we use python list to store datawe should make sure that boundary casessuch as inserting or removing at the beginning or end of the listare properly handled while it is essential to use handcrafted test suitesit is also advantageous to run the program on large collection of randomly generated inputs the random module in python provides several means for generating random numbersor for randomizing the order of collections the dependencies among the classes and functions of program induce hierarchy namelya component is above component in the hierarchy if depends upon bsuch as when function calls function bor function relies on parameter that is an instance of class there are two main testing strategiestop-down and bottom-upwhich differ in the order in which components are tested top-down testing proceeds from the top to the bottom of the program hierarchy it is typically used in conjunction with stubbinga boot-strapping technique that replaces lower-level component with stuba replacement for the component that simulates the functionality of the original for exampleif function calls function to get the first line of filewhen testing we can replace with stub that returns fixed string |
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 another class that depends on the former this form of testing is usually described as unit testingas the functionality of specific component is tested in isolation of the larger software project if used properlythis strategy better isolates the cause of errors to the component being testedas lower-level components upon which it relies should have already been thoroughly tested python provides several forms of support for automated testing when functions or classes are defined in moduletesting for that module can be embedded in the same file the mechanism for doing so was described in section code that is shielded in conditional construct of the form if name =__main__ perform tests will be executed when python is invoked directly on that modulebut not when the module is imported for use in larger software project it is common to put tests in such construct to test the functionality of the functions and classes specifically defined in that module more robust support for automation of unit testing is provided by python' unittest module this framework allows the grouping of individual test cases into larger test suitesand provides support for executing those suitesand reporting or analyzing the results of those tests as software is maintainedthe act of regression testing is usedwhereby all previous tests are re-executed to ensure that changes to the software do not introduce new bugs in previously tested components debugging the simplest debugging technique consists of using print statements to track the values of variables during the execution of the program problem with this approach is that eventually the print statements need to be removed or commented outso they are not executed when the software is finally released better approach is to run the program within debuggerwhich is specialized environment for controlling and monitoring the execution of program the basic functionality provided by debugger is the insertion of breakpoints within the code when the program is executed within the debuggerit stops at each breakpoint while the program is stoppedthe current value of variables can be inspected the standard python distribution includes module named pdbwhich provides debugging support directly within the interpreter most ides for pythonsuch as idleprovide debugging environments with graphical user interfaces |
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 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 |
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 (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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 ( )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 |
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-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 < |
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 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 |
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[ 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 (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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 invariants exercises |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 |
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 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 ( |
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 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 |
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 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 ( |
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 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 |
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 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 |
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 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 |
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 (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 |
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 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 |
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 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 |
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 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( ) |
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 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 |
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 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 |
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 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 |
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 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.