id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
4,000 | some simple numerical programs now that we have covered some basic python constructsit is time to start thinking about how we can combine those constructs to write some simple programs along the waywe'll sneak in few more language constructs and some algorithmic techniques exhaustive enumeration the code in figure prints the integer cube rootif it existsof an integer if the input is not perfect cubeit prints message to that effect #find the cube root of perfect cube int(raw_input('enter an integer')ans while ans** abs( )ans ans if ans** !abs( )print 'is not perfect cubeelseif ans -ans print 'cube root of' ,'is'ans figure using exhaustive enumeration to find the cube root for what values of will this program terminatethe answer is"all integers this can be argued quite simply the value of the expression ans** starts at and gets larger each time through the loop when it reaches or exceeds abs( )the loop terminates since abs(xis always positive there are only finite number of iterations before the loop must terminate whenever you write loopyou should think about an appropriate decrementing function this is function that has the following properties it maps set of program variables into an integer when the loop is enteredits value is nonnegative when its value is <= the loop terminates its value is decreased every time through the loop what is the decrementing function for the loop in figure it is abs(xans** |
4,001 | some simple numerical programs nowlet' insert some errors and see what happens firsttry commenting out the statement ans the python interpreter prints the error messagenameerrorname 'ansis not definedbecause the interpreter attempts to find the value to which ans is bound before it has been bound to anything nowrestore the initialization of ansreplace the statement ans ans by ans ansand try finding the cube root of after you get tired of waitingenter "control (hold down the control key and the key simultaneouslythis will return you to the user prompt in the shell nowadd the statement print 'value of the decrementing function abs(xans** is',abs(xans** at the start of the loopand try running it again (the at the end of the first line of the print statement is used to indicate that the statement continues on the next line this time it will print value of the decrementing function abs(xans** is over and over again the program would have run forever because the loop body is no longer reducing the distance between ans** and abs(xwhen confronted with program that seems not to be terminatingexperienced programmers often insert print statementssuch as the one hereto test whether the decrementing function is indeed being decremented the algorithmic technique used in this program is variant of guess and check called exhaustive enumeration we enumerate all possibilities until we get to the right answer or exhaust the space of possibilities at first blushthis may seem like an incredibly stupid way to solve problem surprisinglyhoweverexhaustive enumeration algorithms are often the most practical way to solve problem they are typically easy to implement and easy to understand andin many casesthey run fast enough for all practical purposes make sure to remove or comment out the print statement that you inserted and reinsert the ans ans statementand then try finding the cube root of the program will seem to finish almost instantaneously nowtry as you can seeeven if millions of guesses are requiredit' not usually problem modern computers are amazingly fast it takes on the order of one nanosecond--one billionth of second--to execute an instruction it' bit hard to appreciate how fast that is for perspectiveit takes slightly more than nanosecond for light to travel single foot ( metersanother way to think about this is that in the time it takes for the sound of your voice to travel hundred feeta modern computer can execute millions of instructions |
4,002 | just for funtry executing the code max int(raw_input('enter postive integer') while maxi print see how large an integer you need to enter before there is perceptible pause before the result is printed finger exercisewrite program that asks the user to enter an integer and prints two integersroot and pwrsuch that pwr and root**pwr is equal to the integer entered by the user if no such pair of integers existsit should print message to that effect for loops the while loops we have used so far are highly stylized each iterates over sequence of integers python provides language mechanismthe for loopthat can be used to simplify programs containing this kind of iteration the general form of for statement is (recall that the words in italics are descriptions of what can appearnot actual code)for variable in sequencecode block the variable following for is bound to the first value in the sequenceand the code block is executed the variable is then assigned the second value in the sequenceand the code block is executed again the process continues until the sequence is exhausted or break statement is executed within the code block the sequence of values bound to variable is most commonly generated using the built-in function rangewhich returns sequence containing an arithmetic progression the range function takes three integer argumentsstartstopand step it produces the progression startstart stepstart *stepetc if step is positivethe last element is the largest integer start *step less than stop if step is negativethe last element is the smallest integer start *step greater than stop for examplerange( produces the sequence [ ]and range( - produces the sequence [ if the first argument is omitted it defaults to and if the last argument (the step sizeis omitted it defaults to for examplerange( and range( both produce the sequence [ less commonlywe specify the sequence to be iterated over in for loop by using literale [ in python range generates the entire sequence when it is invoked thereforefor examplethe expression range( uses quite lot of memory this can be avoided by using the |
4,003 | some simple numerical programs built-in function xrange instead of rangesince xrange generates the values only as they are needed by the for loop consider the code for in range( )print it prints nowthink about the code for in range( )print it raises the question of whether changing the value of inside the loop affects the number of iterations it does not the range function in the line with for is evaluated just before the first iteration of the loopand not reevaluated for subsequent iterations to see how this worksconsider for in range( )for in range( )print it prints because the range function in the outer loop is evaluated only oncebut the range function in the inner loop is evaluated each time the inner for statement is reached the code in figure reimplements the exhaustive enumeration algorithm for finding cube roots the break statement in the for loop causes the loop to terminate before it has been run on each element in the sequence over which it is iterating when executeda break statement exits the innermost loop in which it is enclosed in python range behaves the way xrange behaves in python |
4,004 | #find the cube root of perfect cube int(raw_input('enter an integer')for ans in range( abs( )+ )if ans** >abs( )break if ans** !abs( )print 'is not perfect cubeelseif ans -ans print 'cube root of' ,'is'ans figure using for and break statements the for statement can be used to conveniently iterate over characters of string for exampletotal for in ' 'total total int(cprint total sums the digits in the string denoted by the literal ' and prints the total finger exerciselet be string that contains sequence of decimal numbers separated by commase ' , , write program that prints the sum of the numbers in approximate solutions and bisection search imagine that someone asks you to write program that finds the square root of any nonnegative number what should you doyou should probably start by saying that you need better problem statement for examplewhat should the program do if asked to find the square root of the square root of is not rational number this means that there is no way to precisely represent its value as finite string of digits (or as float)so the problem as initially stated cannot be solved the right thing to have asked for is program that finds an approximation to the square root-- an answer that is close enough to the actual square root to be useful we will return to this issue in considerable detail later in the book but for nowlet' think of "close enoughas an answer that lies within some constantcall it epsilonof the actual answer the code in figure implements an algorithm that finds an approximation to square root it uses an operator+=that we have not previously used the code ans +step is semantically equivalent to the more verbose code ans ans+step the operators -and *work similarly |
4,005 | some simple numerical programs epsilon step epsilon** numguesses ans while abs(ans** >epsilon and ans <xans +step numguesses + print 'numguesses ='numguesses if abs(ans** >epsilonprint 'failed on square root of' elseprint ans'is close to square root of' figure approximating the square root using exhaustive enumeration once againwe are using exhaustive enumeration notice that this method for finding the square root has nothing in common with the way of finding square roots using pencil that you might have learned in middle school it is often the case that the best way to solve problem with computer is quite different from how one would approach the problem by hand when the code is runit prints numguesses is close to square root of should we be disappointed that the program didn' figure out that is perfect square and print no the program did what it was intended to do though it would have been ok to print doing so is no better than printing any value close enough to what do you think will happen if we set will it find root close to nope exhaustive enumeration is search technique that works only if the set of values being searched includes the answer in this casewe are enumerating the values between and when is between and the square root of does not lie in this interval one way to fix this is to change the first line of the while loop to while abs(ans** >epsilon and ans*ans <xnowlet' think about how long the program will take to run the number of iterations depends upon how close the answer is to zero and on the size of the steps roughly speakingthe program will execute the while loop at most /step times let' try the code on something biggere it will run for bitand then print numguesses failed on square root of what do you think happenedsurely there exists floating point number that approximates the square root of to within why didn' our program find itthe problem is that our step size was too largeand the program skipped over all the suitable answers try making step equal to epsilon** and |
4,006 | running the program it will eventually find suitable answerbut you might not have the patience to wait for it to do so roughly how many guesses will it have to makethe step size will be and the square root of is around this means that the program will have to make in the neighborhood of , , guesses to find satisfactory answer we could try to speed it up by starting closer to the answerbut that presumes that we know the answer the time has come to look for different way to attack the problem we need to choose better algorithm rather than fine tune the current one but before doing solet' look at problem thatat first blushappears to be completely different from root finding consider the problem of discovering whether word starting with given sequence of letters appears in some hard-copy dictionary of the english language exhaustive enumeration wouldin principlework you could start at the first word and examine each word until either you found word starting with the sequence of letters or you ran out of words to examine if the dictionary contained wordsit wouldon averagetake / probes to find the word if the word were not in the dictionaryit would take probes of coursethose who have had the pleasure of actually looking word up in physical (rather than onlinedictionary would never proceed in this way fortunatelythe folks who publish dictionaries go to the trouble of putting the words in lexicographical order this allows us to open the book to page where we think the word might lie ( near the middle for words starting with the letter mif the sequence of letters lexicographically precedes the first word on the pagewe know to go backwards if the sequence of letters follows the last word on the pagewe know to go forwards otherwisewe check whether the sequence of letters matches word on the page now let' take the same idea and apply it the problem of finding the square root of suppose we know that good approximation to the square root of lies somewhere between and max we can exploit the fact that numbers are totally ordered that is to sayfor any pair of distinct numbersn and either sowe can think of the square root of as lying somewhere on the line max and start searching that interval since we don' necessarily know where to start searchinglet' start in the middle guessmax if that is not the right answer (and it won' be most of the time)ask whether it is too big or too small if it is too bigwe know that the answer must lie to the left if it is too smallwe know that the answer must lie to the right we then repeat the process on the smaller interval figure contains an implementation and test of this algorithm |
4,007 | some simple numerical programs epsilon numguesses low high max( xans (high low)/ while abs(ans** >epsilonprint 'low ='low'high ='high'ans ='ans numguesses + if ans** xlow ans elsehigh ans ans (high low)/ print 'numguesses ='numguesses print ans'is close to square root of' figure using bisection search to approximate square root when runit prints low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans low high ans numguesses is close to square root of notice that it finds different answer than our earlier algorithm that is perfectly finesince it still meets the problem statement more importantnotice that at each iteration the size of the space to be searched is cut in half because it divides the search space in half at each stepit is called bisection search bisection search is huge improvement over our earlier algorithmwhich reduced the search space by only small amount at each iteration let us try again this time the program takes only thirty guesses to find an acceptable answer how about it takes only forty-five guesses there is nothing special about the fact that we are using this algorithm to find square roots for exampleby changing couple of ' to 'swe can use it to approximate cube root of nonnegative number in the next we will introduce language mechanism that allows us to generalize this code to find any root finger exercisewhat would the code in figure do if the statement were replaced by - |
4,008 | finger exercisewhat would have to be changed to make the code in figure work for finding an approximation to the cube root of both negative and positive numbers(hintthink about changing low to ensure that the answer lies within the region being searched few words about using floats most of the timenumbers of type float provide reasonably good approximation to real numbers but "most of the timeis not all of the timeand when they don' it can lead to surprising consequences for exampletry running the code for in range( ) if = print ' elseprint 'is not perhaps youlike most peoplefind it doubly surprising that it prints is not why does it get to the else clause in the first placeand if it somehow does get therewhy is it printing such nonsensical phraseto understand why this happenswe need to understand how floating point numbers are represented in the computer during computation to understand thatwe need to understand binary numbers when you first learned about decimal numbersi numbers base you learned that decimal number is represented by sequence of the digits the rightmost digit is the placethe next digit towards the left the placeetc for examplethe sequence of decimal digits represents * * * how many different numbers can be represented by sequence of length na sequence of length one can represent any one of ten numbers ( sequence of length two can represent one hundred different numbers ( - more generallywith sequence of length none can represent different numbers binary numbers--numbers base --work similarly binary number is represented by sequence of digits each of which is either or these digits are often called bits the rightmost digit is the placethe next digit towards the left the placeetc for examplethe sequence of binary digits represents * * * how many different numbers can be represented by sequence of length finger exercisewhat is the decimal equivalent of the binary number |
4,009 | some simple numerical programs perhaps because most people have ten fingerswe seem to like to use decimals to represent numbers on the other handall modern computer systems represent numbers in binary this is not because computers are born with two fingers it is because it is easy to build hardware switchesi devices that can be in only one of two stateson or off that the computer uses binary representation and people decimal representation can lead to occasional cognitive dissonance in almost modern programming languages non-integer numbers are implemented using representation called floating point for the momentlet' pretend that the internal representation is in decimal we would represent number as pair of integers--the significant digits of the number and an exponent for examplethe number would be represented as the pair ( - )which stands for the product - the number of significant digits determines the precision with which numbers can be represented if for examplethere were only two significant digitsthe number could not be represented exactly it would have to be converted to some approximation of in this case that approximation is called the rounded value modern computers use binarynot decimalrepresentations we represent the significant digits and exponents in binary rather than decimal and raise rather than to the exponent for examplethe number ( / would be represented as the pair ( - )because / is in binary and - is the binary representation of - the pair ( - stands for - / what about the decimal fraction / which we write in python as the best we can do with four significant binary digits is ( - this is equivalent to / if we had five significant binary digitswe would represent as ( - )which is equivalent to / how many significant digits would we need to get an exact floating point representation of an infinite number of digitsthere do not exist integers sig and exp such that sig -exp equals so no matter how many bits python (or any other languagechooses to use to represent floating point numbersit will be able to represent only an approximation to in most python implementationsthere are bits of precision available for floating point numbersso the significant digits stored for the decimal number will be this is equivalent to the decimal number pretty close to / but not exactly / |
4,010 | returning to the original mysterywhy does for in range( ) if = print ' elseprint 'is not print is not we now see that the test = produces the result false because the value to which is bound is not exactly what gets printed if we add to the end of the else clause the code print = * it prints false because during at least one iteration of the loop python ran out of significant digits and did some rounding it' not what our elementary school teachers taught usbut adding ten times does not produce the same value as multiplying by finallywhy does the code print print rather than the actual value of the variable xbecause the designers of python thought that would be convenient for users if print did some automatic rounding this is probably an accurate assumption most of the time howeverit is important to keep in mind that what is being displayed does not necessarily exactly match the value stored in the machine by the wayif you want to explicitly round floating point numberuse the round function the expression round(xnumdigitsreturns the floating point number equivalent to rounding the value of to numdigits decimal digits following the decimal point for example print round( ** will print as an approximation to the square root of does the difference between real and floating point numbers really mattermost of the timemercifullyit does not howeverone thing that is almost always worth worrying about is tests for equality as we have seenusing =to compare two floating point values can produce surprising result it is almost always more appropriate to ask whether two floating point values are close enough to each othernot whether they are identical sofor exampleit is better to write abs( - rather than = another thing to worry about is the accumulation of rounding errors most of the time things work out ok because sometimes the number stored in the computer is little bigger than intendedand sometimes it is little smaller than intended howeverin some programsthe errors will all be in the same direction and accumulate over time |
4,011 | some simple numerical programs newton-raphson the most commonly used approximation algorithm is usually attributed to isaac newton it is typically called newton' methodbut is sometimes referred to as the newton-raphson method it can be used to find the real roots of many functionsbut we shall look at it only in the context of finding the real roots of polynomial with one variable the generalization to polynomials with multiple variables is straightforward both mathematically and algorithmically polynomial with one variable (by conventionwe will write the variable as xis either zero or the sum of finite number of nonzero termse each terme consists of constant (the coefficient of the term in this casemultiplied by the variable ( in this caseraised to nonnegative integer exponent ( in this casethe exponent on variable in term is called the degree of that term the degree of polynomial is the largest degree of any single term some examples are (degree ) (degree )and (degree in contrast / and are not polynomials if is polynomial and real numberwe will write (rto stand for the value of the polynomial when root of the polynomial is solution to the equation an such that ( sofor examplethe problem of finding an approximation to the square root of can be formulated as finding an such that newton proved theorem that implies that if valuecall it guessis an approximation to root of polynomialthen guess (guess)/ '(guess)where pis the first derivative of pis better approximation for any constant and any coefficient cthe first derivative of cx is cx for examplethe first derivative of is thereforewe know that we can improve on the current guesscall it yby choosing as our next guess ( )/ this is called successive approximation figure contains code illustrating how to use this idea to quickly find an approximation to the square root joseph raphson published similar method about the same time as newton the first derivative of function (xcan be thought of as expressing how the value of (xchanges with respect to changes in if you haven' previously encountered derivativesdon' worry you don' need to understand themor for that matter polynomialsto understand the implementation of newton' method |
4,012 | #newton-raphson for square root #find such that ** is within epsilon of epsilon guess / while abs(guess*guess >epsilonguess guess (((guess** )/( *guess)print 'square root of' 'is about'guess figure newton-raphson method finger exerciseadd some code to the implementation of newton-raphson that keeps track of the number of iterations used to find the root use that code as part of program that compares the efficiency of newton-raphson and bisection search (you should discover that newton-raphson is more efficient |
4,013 | so farwe have introduced numbersassignmentsinput/outputcomparisonsand looping constructs how powerful is this subset of pythonin theoretical senseit is as powerful as you will ever need such languages are called turing complete this means that if problem can be solved via computationit can be solved using only those statements you have already seen which isn' to say that you should use only these statements at this point we have covered lot of language mechanismsbut the code has been single sequence of instructionsall merged together for examplein the last we looked at the code in figure epsilon numguesses low high max( xans (high low)/ while abs(ans** >epsilonnumguesses + if ans** xlow ans elsehigh ans ans (high low)/ print 'numguesses ='numguesses print ans'is close to square root of' figure using bisection search to approximate square root this is reasonable piece of codebut it lacks general utility it works only for values denoted by the variables and epsilon this means that if we want to reuse itwe need to copy the codepossibly edit the variable namesand paste it where we want it because of this we cannot easily use this computation inside of some othermore complexcomputation furthermoreif we want to compute cube roots rather than square rootswe have to edit the code if we want program that computes both square and cube roots (or for that matter square roots in two different places)the program would contain multiple chunks of almost identical code this is very bad thing the more code program containsthe more chance there is for something to go wrongand the harder the code is to maintain imaginefor examplethat there was an error in the initial implementation of square rootand that the error came to light when testing the program it would be all too easy to fix the implementation of square root in one place and forget that there was similar code elsewhere that was also in need of repair python provides several linguistic features that make it relatively easy to generalize and reuse code the most important is the function |
4,014 | functions and scoping we've already used number of built-in functionse max and abs in figure the ability for programmers to define and then use their own functionsas if they were built-inis qualitative leap forward in convenience function definitions in python each function definition is of the form def name of function (list of formal parameters)body of function for examplewe could define the function max by the code def max(xy)if yreturn elsereturn def is reserved word that tells python that function is about to be defined the function name (max in this exampleis simply name that is used to refer to the function the sequence of names ( , in this examplewithin the parentheses following the function name are the formal parameters of the function when the function is usedthe formal parameters are bound (as in an assignment statementto the actual parameters (often referred to as argumentsof the function invocation (also referred to as function callfor examplethe invocation max( binds to and to the function body is any piece of python code there ishowevera special statementreturnthat can be used only within the body of function function call is an expressionand like all expressions it has value that value is the value returned by the invoked function for examplethe value of the expression max( , )*max( , is because the first invocation of max returns the int and the second returns the int note that execution of return statement terminates that invocation of the function to recapitulatewhen function is called the expressions that make up the actual parameters are evaluatedand the formal parameters of the function are bound to the resulting values for examplethe invocation max( + zwill bind the formal parameter to and the formal parameter to whatever value the variable has when the invocation is evaluated recall that italics is used to describe python code in practiceyou would probably use the built-in function maxrather than define your own |
4,015 | functionsscopingand abstraction the point of execution (the next instruction to be executedmoves from the point of invocation to the first statement in the body of the function the code in the body of the function is executed until either return statement is encounteredin which case the value of the expression following the return becomes the value of the function invocationor there are no more statements to executein which case the function returns the value none (if no expression follows the returnthe value of the invocation is none the value of the invocation is the returned value the point of execution is transferred back to the code immediately following the invocation parameters provide something called lambda abstraction, allowing programmers to write code that manipulates not specific objectsbut instead whatever objects the caller of the function chooses to use as actual parameters finger exercisewrite function isin that accepts two strings as arguments and returns true if either string occurs anywhere in the otherand false otherwise hintyou might want to use the built-in str operation in keyword arguments and default values in pythonthere are two ways that formal parameters get bound to actual parameters the most common methodwhich is the only one we have used thus faris called positional--the first formal parameter is bound to the first actual parameterthe second formal to the second actualetc python also supports what it calls keyword argumentsin which formals are bound to actuals using the name of the formal parameter consider the function definition in figure the function printname assumes that firstname and lastname are strings and that reverse is boolean if reverse =trueit prints lastnamefirstnameotherwise it prints firstname lastname def printname(firstnamelastnamereverse)if reverseprint lastname 'firstname elseprint firstnamelastname figure function that prints name each of the following is an equivalent invocation of printnameprintname('olga''puchmajerova'falseprintname('olga''puchmajerova'falseprintname('olga''puchmajerova'reverse falseprintname('olga'lastname 'puchmajerova'reverse falseprintname(lastname='puchmajerova'firstname='olga'reverse=false the name "lambda abstractionis derived from some mathematics developed by alonzo church in the and |
4,016 | though the keyword arguments can appear in any order in the list of actual parametersit is not legal to follow keyword argument with non-keyword argument thereforean error message would be produced by printname('olga'lastname 'puchmajerova'falsekeyword arguments are commonly used in conjunction with default parameter values we canfor examplewrite def printname(firstnamelastnamereverse false)if reverseprint lastname 'firstname elseprint firstnamelastname default values allow programmers to call function with fewer than the specified number of arguments for exampleprintname('olga''puchmajerova'printname('olga''puchmajerova'trueprintname('olga''puchmajerova'reverse truewill print olga puchmajerova puchmajerovaolga puchmajerovaolga the last two invocations of printname are semantically equivalent the last one has the advantage of providing some documentation for the perhaps mysterious parameter true scoping let' look at another small exampledef ( )#name used as formal parameter print ' =' return ( #value of used as actual parameter print ' =' print ' =' print ' =' when runthis code printsx what is going on hereat the call of fthe formal parameter is locally bound to the value of the actual parameter it is important to note that though the actual and formal parameters have the same namethey are not the same variable each function defines new name spacealso called scope the |
4,017 | functionsscopingand abstraction formal parameter and the local variable that are used in exist only within the scope of the definition of the assignment statement within the function body binds the local name to the object the assignments in have no effect at all on the bindings of the names and that exist outside the scope of here' one way to think about thisat top leveli the level of the shella symbol table keeps track of all names defined at that level and their current bindings when function is calleda new symbol table (sometimes called stack frameis created this table keeps track of all names defined within the function (including the formal parametersand their current bindings if function is called from within the function bodyyet another stack frame is created when the function completesits stack frame goes away in pythonone can always determine the scope of name by looking at the program text this is called static or lexical scoping figure contains slightly more elaborate example def ( )def () 'abcprint ' =' def () print ' =' print ' =' ( (print ' =' return (xprint ' =' print ' =' (figure nested scopes the history of the stack frames associated with the code in figure is depicted in figure |
4,018 | figure stack frames the first column contains the set of names known outside the body of the function fi the variables and zand the function name the first assignment statement binds to the assignment statement (xfirst evaluates the expression (xby invoking the function with the value to which is bound when is entereda stack frame is createdas shown in column the names in the stack frame are (the formal parameternot the in the calling context) and the variables and are bound to objects of type function the properties of each of these functions are given by the function definitions within when is invoked from within fyet another stack frame is createdas shown in column this frame contains only the local variable why does it not also contain xa name is added to the scope associated with function only if that name is either formal parameter of the function or variable that is bound to an object within the body of the function in the body of hx occurs only on the right-hand side of an assignment statement the appearance of name ( in this casethat is not bound anywhere in the function body (the body of hcauses the interpreter to search the previous stack frame associated with the scope within which the function is defined (the stack frame associated with fif the name is found (which it is in this casethe value to which it is bound ( is used if it is not found therean error message is produced when returnsthe stack frame associated with the invocation of goes away ( it is popped off the top of the stack)as depicted in column note that we never remove frames from the middle of the stackbut only the most recently added frame it is because it has this "last in first outbehavior that we refer to it as stack (think of stack of trays waiting to be taken in cafeterianext is invokedand stack frame containing ' local variable is added (column when returnsthat frame is popped (column when returnsthe stack frame containing the names associated with is poppedgetting us back to the original stack frame (column notice that when returnseven though the variable no longer existsthe object of type function to which that name was once bound still exists this is |
4,019 | functionsscopingand abstraction because functions are objectsand can be returned just like any other kind of object soz can be bound to the value returned by fand the function call (can be used to invoke the function that was bound to the name within --even though the name is not known outside the context of sowhat does the code in figure printit prints abc abc the order in which references to name occur is not germane if an object is bound to name anywhere in the function body (even if it occurs in an expression before it appears as the left-hand-side of an assignment)it is treated as local to that function considerfor examplethe code def ()print def ()print ( (it prints when is invokedbut an error message is printed when it encounters the print statement in because the assignment statement following the print statement causes to be local to and because is local to git has no value when the print statement is executed confused yetit takes most people bit of time to get their head around scope rules don' let this bother you for nowcharge ahead and start using functions most of the time you will find that you only want to use variables that are local to functionand the subtleties of scoping will be irrelevant the wisdom of this language design decision is debatable |
4,020 | specifications figure defines functionfindrootthat generalizes the bisection search we used to find square roots in figure it also contains functiontestfindrootthat can be used to test whether or not findroot works as intended the function testfindroot is almost as long as findroot itself to inexperienced programmerswriting test functions such as this often seems to be waste of effort experienced programmers knowhoweverthat an investment in writing testing code often pays big dividends it certainly beats typing test cases into the shell over and over again during debugging (the process of finding out why program does not workand then fixing itit also forces us to think about which tests are likely to be most illuminating the text between the triple quotation marks is called docstring in python by conventionpython programmers use docstrings to provide specifications of functions these docstrings can be accessed using the built-in function help if we enter the shell and type help(abs)the system will display help on built-in function abs in module __builtin__absabs(number-number return the absolute value of the argument if the code in figure (belowhas been loaded into idletyping help(findrootin the shell will display help on function findroot in module __main__findroot(xpowerepsilonassumes and epsilon int or floatpower an intepsilon power > returns float such that **power is within epsilon of if such float does not existit returns none if we type findrootin either the shell or the editorthe list of formal parameters and the first line of the docstring will be displayed |
4,021 | functionsscopingand abstraction def findroot(xpowerepsilon)"""assumes and epsilon int or floatpower an intepsilon power > returns float such that **power is within epsilon of if such float does not existit returns none""if and power% = return none low min(- xhigh max( xans (high low)/ while abs(ans**power >epsilonif ans**power xlow ans elsehigh ans ans (high low)/ return ans def testfindroot()epsilon for in ( - - - )for power in range( )print 'testing str( +and power str(powerresult findroot(xpowerepsilonif result =noneprint no rootelseprint 'result**power'~=' figure finding an approximation to root specification of function defines contract between the implementer of function and those who will be writing programs that use the function we will refer to the users of function as its clients this contract can be thought of as containing two parts assumptionsthese describe conditions that must be met by clients of the function typicallythey describe constraints on the actual parameters almost alwaysthey specify the acceptable set of types for each parameterand not infrequently some constraints on the value of one or more of the parameters for examplethe first two lines of the docstring of findroot describe the assumptions that must be satisfied by clients of findroot guaranteesthese describe conditions that must be met by the functionprovided that it has been called in way that satisfies the assumptions the last two lines of the docstring of findroot describe the guarantees that the implementation of the function must meet functions are way of creating computational elements that we can think of as primitives just as we have the built-in functions max and abswe would like to have the equivalent of built-in function for finding roots and for many other complex operations functions facilitate this by providing decomposition and abstraction |
4,022 | decomposition creates structure it allows us to break problem into modules that are reasonably self-containedand that may be reused in different settings abstraction hides detail it allows us to use piece of code as if it were black box--that issomething whose interior details we cannot seedon' need to seeand shouldn' even want to see the essence of abstraction is preserving information that is relevant in given contextand forgetting information that is irrelevant in that context the key to using abstraction effectively in programming is finding notion of relevance that is appropriate for both the builder of an abstraction and the potential clients of the abstraction that is the true art of programming abstraction is all about forgetting there are lots of ways to model thisfor examplethe auditory apparatus of most teenagers teenager saysmay borrow the car tonightparent saysyesbut be back before midnightand make sure that the gas tank is full teenager hearsyes the teenager has ignored all of those pesky details that he or she considers irrelevant abstraction is many-to-one process had the parent said yesbut be back before : and make sure that the car is cleanit would also have been abstracted to yes by way of analogyimagine that you were asked to produce an introductory computer science course containing twenty-five lectures one way to do this would be to recruit twenty-five professorsand ask each of them to prepare fifty-minute lecture on their favorite topic though you might get twenty-five wonderful hoursthe whole thing is likely to feel like dramatization of pirandello' "six characters in search of an author(or that political science course you took with fifteen guest lecturersif each professor worked in isolationthey would have no idea how to relate the material in their lecture to the material covered in other lectures somehowone needs to let everyone know what everyone else is doingwithout generating so much work that nobody is willing to participate this is where abstraction comes in you could write twenty-five specificationseach saying what material the students should learn in each lecturebut not giving any detail about how that material should be taught what you got might not be pedagogically wonderfulbut at least it might make sense this is the way organizations go about using teams of programmers to get things done given specification of modulea programmer can work on implementing that module without worrying unduly about what the other programmers on the team are doing moreoverthe other programmers can use the specification to start writing code that uses that module without worrying unduly about how that module is to be implemented "where ignorance is bliss'tis folly to be wise "--thomas gray |
4,023 | functionsscopingand abstraction the specification of findroot is an abstraction of all the possible implementations that meet the specification clients of findroot can assume that the implementation meets the specificationbut they should assume nothing more for exampleclients can assume that the call findroot( returns some value whose square is between and the value returned could be positive or negativeand even though is perfect square the value returned might not be or - recursion you may have heard of recursionand in all likelihood think of it as rather subtle programming technique that' an urban legend spread by computer scientists to make people think that we are smarter than we really are recursion is very important ideabut it' not so subtleand it is more than programming technique as descriptive method recursion is widely usedeven by people who would never dream of writing program consider part of the legal code of the united states defining the notion of "natural-borncitizen roughly speakingthe definition is as follows any child born inside the united states any child born in wedlock outside the united states both of whose parents are citizens of the as long as one parent has lived in the prior to the birth of the childand any child born in wedlock outside the united states one of whose parents is citizen who has lived at least five years in the prior to the birth of the childprovided that at least two of those years were after the citizen' fourteenth birthday the first part is simpleif you are born in the united statesyou are naturalborn citizen (such as barack obamaif you are not born in the then one has to decide if your parents are citizens (either natural born or naturalizedto determine if your parents are citizensyou might have to look at your grandparentsand so on in generala recursive definition is made up of two parts there is at least one base case that directly specifies the result for special case (case in the example above)and there is at least one recursive (inductivecase (cases and in the example abovethat defines the answer in terms of the answer to the question on some other inputtypically simpler version of the same problem |
4,024 | the world' simplest recursive definition is probably the factorial function (typically written in mathematics using !on natural numbers the classic inductive definition is ( )( nthe first equation defines the base case the second equation defines factorial for all natural numbersexcept the base casein terms of the factorial of the previous number figure contains both an iterative (factiand recursive (factrimplementation of factorial def facti( )"""assumes that is an int returns !""result while result result - return result def factr( )"""assumes that is an int returns !""if = return elsereturn *factr( figure iterative and recursive implementations of factorial this function is sufficiently simple that neither implementation is hard to follow stillthe second is more obvious translation of the original recursive definition it almost seems like cheating to implement factr by calling factr from within the body of factr it works for the same reason that the iterative implementation works we know that the iteration in facti will terminate because starts out positive and each time around the loop it is reduced by this means that it cannot be greater than forever similarlyif factr is called with it returns value without making recursive call when it does make recursive callit always does so with value one less than the value with which it was called eventuallythe recursion terminates with the call factr( fibonacci numbers the fibonacci sequence is another common mathematical function that is usually defined recursively "they breed like rabbits,is often used to describe population that the speaker thinks is growing too quickly in the year the the exact definition of "natural numberis subject to debate some define it as the positive integers and others as the nonnegative integers that' why we were explicit about the possible values of in the docstring in figure |
4,025 | functionsscopingand abstraction italian mathematician leonardo of pisaalso known as fibonaccideveloped formula designed to quantify this notionalbeit with some not terribly realistic assumptions suppose newly born pair of rabbitsone male and one femaleare put in pen (or worsereleased in the wildsuppose further that the rabbits are able to mate at the age of one month (whichastonishinglysome breeds canand have one-month gestation period (whichastonishinglysome breeds dofinallysuppose that these mythical rabbits never dieand that the female always produces one new pair (one maleone femaleevery month from its second month on how many pregnant rabbits will there be at the end of six monthson the last day of the first month (call it month )there will be one female (ready to conceive on the first day of the next monthon the last day of the second monththere will still be only one female (since she will not give birth until the first day of the next monthon the last day of the next monththere will be two females (one pregnant and one noton the last day of the next monththere will be three females (two pregnant and one notand so on let' look at this progression in tabular form notice that in this tablefor month females(nfemales( - females( - this is not an accident each female that was alive in month - will still be alive in month in additioneach female that was alive in month - will produce one new female in month the new females can be added to the females alive in month - to get the number of females in month the growth in population is described naturally by the recurrencefemales( females( females( females( + females(nmonth females this definition is little different from the recursive definition of factorialit has two base casesnot just one in generalyou can have as many base cases as you need in the recursive casethere are two recursive callsnot just one againthere can be as many as you need figure contains straightforward implementation of the fibonacci recurrence, along with function that can be used to test it while obviously correctthis is terribly inefficient implementation of the fibonacci function there is simple iterative implemenentation that is much better |
4,026 | def fib( )"""assumes an int > returns fibonacci of ""if = or = return elsereturn fib( - fib( - def testfib( )for in range( + )print 'fib of' '='fib(ifigure recursive implementation of fibonacci sequence writing the code is the easy part of solving this problem once we went from the vague statement of problem about bunnies to set of recursive equationsthe code almost wrote itself finding some kind of abstract way to express solution to the problem at hand is very often the hardest step in building useful program we will talk much more about this later in the book as you might guessthis is not perfect model for the growth of rabbit populations in the wild in thomas austinan australian farmerimported twenty-four rabbits from englandto be used as targets in hunts ten years laterapproximately two million rabbits were shot or trapped each year in australiawith no noticeable impact on the population that' lot of rabbitsbut not anywhere close to the th fibonacci number though the fibonacci sequence does not actually provide perfect model of the growth of rabbit populationsit does have many interesting mathematical properties fibonacci numbers are also quite common in nature finger exercisewhen the implementation of fib in figure is used to compute fib( )how many times does it compute the value fib( ) the damage done by the descendants of those twenty-four cute bunnies has been estimated to be $ million per yearand they are in the process of eating many native plants into extinction that we call this fibonacci sequence is an example of eurocentric interpretation of history fibonacci' great contribution to european mathematics was his book liber abaciwhich introduced to european mathematicians many concepts already well known to indian and arabic scholars these concepts included hindu-arabic numerals and the decimal system what we today call the fibonacci sequence was taken from the work of the sanskrit mathematician pingala if you are feeling especially geekytry writing fibonacci poem this is form of poetry in which the number of syllables in each line is equal to the total number of syllables in the previous two lines think of the first line (which has zero syllablesas place to take deep breath before starting to read your poem |
4,027 | functionsscopingand abstraction palindromes recursion is also useful for many problems that do not involve numbers figure contains functionispalindromethat checks whether string reads the same way backwards and forwards def ispalindrome( )"""assumes is str returns true if the letters in form palindromefalse otherwise non-letters and capitalization are ignored ""def tochars( ) lower(letters 'for in sif in 'abcdefghijklmnopqrstuvwxyz'letters letters return letters def ispal( )if len( < return true elsereturn [ = [- and ispal( [ :- ]return ispal(tochars( )figure palindrome testing the function ispalindrome contains two internal helper functions this should be of no interest to clients of the functionwho should care only that ispalindrome meets its specification but you should carebecause there are things to learn by examining the implementation the helper function tochars converts all letters to lowercase and removes all non-letters it starts by using built-in method on strings to generate string that is identical to sexcept that all uppercase letters have been converted to lowercase we will talk lot more about method invocation when we get to classes for nowthink of it as peculiar syntax for function call instead of putting the first (and in this case onlyargument inside parentheses following the function namewe use dot notation to place that argument before the function name the helper function ispal uses recursion to do the real work the two base cases are strings of length zero or one this means that the recursive part of the implementation is reached only on strings of length two or more the conjunction in the else clause is evaluated from left to right the code first checks whether the first and last characters are the sameand if they are goes on to check whether the string minus those two characters is palindrome that the second conjunct is not evaluated unless the first conjunct evaluates to when two boolean-valued expressions are connected by "and,each expression is called conjunct if they are connected by "or,they are called disjuncts |
4,028 | true is semantically irrelevant in this example howeverlater in the book we will see examples where this kind of short-circuit evaluation of boolean expressions is semantically relevant this implementation of ispalindrome is an example of problem-solving principle known as divide-and-conquer (this principle is related to but different from divide-and-conquer algorithmswhich are discussed in the problem-solving principle is to conquer hard problem by breaking it into set of subproblems with the properties that the subproblems are easier to solve than the original problemand solutions of the subproblems can be combined to solve the original problem in this casewe solve the problem by breaking the original problem into simpler version of the same problem (checking whether shorter string is palindrome)plus some simple things we know how to do (comparing single charactersfigure contains some code that can be used to visualize how this works def ispalindrome( )"""assumes is str returns true if is palindromefalse otherwise punctuation marksblanksand capitalization are ignored ""def tochars( ) lower(letters 'for in sif in 'abcdefghijklmnopqrstuvwxyz'letters letters return letters def ispal( )print ispal called with' if len( < print about to return true from base casereturn true elseanswer [ = [- and ispal( [ :- ]print about to return'answer'for' return answer return ispal(tochars( )def testispalindrome()print 'try doggodprint ispalindrome('doggod'print 'try dogoodprint ispalindrome('dogood'figure code to visualize palindrome testing |
4,029 | functionsscopingand abstraction when the code in figure is runit will print try doggod ispal called with doggod ispal called with oggo ispal called with gg ispal called with about to return true from base case about to return true for gg about to return true for oggo about to return true for doggod true try dogood ispal called with dogood ispal called with ogoo ispal called with go about to return false for go about to return false for ogoo about to return false for dogood false divide-and-conquer is very old idea julius caesar practiced what the romans referred to as divide et impera (divide and rulethe british practiced it brilliantly to control the indian subcontinent benjamin franklin was well aware of the british expertise in using this techniqueprompting him to say at the signing of the declaration of independence"we must all hang togetheror assuredly we shall all hang separately global variables if you tried calling fib with large numberyou probably noticed that it took very long time to run suppose we want to know how many recursive calls are madewe could do careful analysis of the code and figure it outand in we will talk about how to do that another approach is to add some code that counts the number of calls one way to do that uses global variables until nowall of the functions we have written communicate with their environment solely through their parameters and return values for the most partthis is exactly as it should be it typically leads to programs that are relatively easy to readtestand debug every once in whilehoweverglobal variables come in handy consider the code in figure |
4,030 | def fib( )"""assumes an int > returns fibonacci of ""global numfibcalls numfibcalls + if = or = return elsereturn fib( - fib( - def testfib( )for in range( + )global numfibcalls numfibcalls print 'fib of' '='fib(iprint 'fib called'numfibcalls'times figure using global variable in each functionthe line of code global numfibcalls tells python that the name numcalls should be defined at the outermost scope of the module (see section in which the line of code appears rather than within the scope of the function in which the line of code appears--despite the fact that numfibcalls occurs on the left-hand side of an assignment statement in both fib and testfib (had we not included the code global numfibcallsthe name numfibcalls would have been local to each of fib and testfib the functions fib and testfib both have unfettered access to the object referenced by the variable numfibcalls the function testfib binds numfibcalls to each time it calls fiband fib increments the value of numfibcalls each time fib is entered it is with some trepidation that we introduce the topic of global variables since the card-carrying computer scientists have inveighed against them the indiscriminate use of global variables can lead to lots of problems the key to making programs readable is locality one reads program piece at timeand the less context needed to understand each piecethe better since global variables can be modified or read in wide variety of placesthe sloppy use of them can destroy locality neverthelessthere are times when they are just what is needed modules so farwe have operated under the assumption that our entire program is stored in one file this is perfectly reasonable as long as programs are small as programs get largerhoweverit is typically more convenient to store different parts of them in different files imaginefor examplethat multiple people are working on the same program it would be nightmare if they were all trying to update the same file python modules allow us to easily construct program from code in multiple files module is py file containing python definitions and statements we could createfor examplea file circle py containing |
4,031 | functionsscopingand abstraction pi def area(radius)return pi*(radius** def circumference(radius)return *pi*radius def spheresurface(radius)return *area(radiusdef spherevolume(radius)return )*pi*(radius** program gets access to module through an import statement sofor examplethe code import circle print circle pi print circle area( print circle circumference( print circle spheresurface( will print modules are typically stored in individual files each module has its own private symbol table consequentlywithin circle py we access objects ( pi and areain the usual way executing import creates binding for module in the scope in which the importation occurs thereforein the importing context we use dot notation to indicate that we are referring to name defined in the imported module for exampleoutside of circle pythe references pi and circle pi can (and in this case dorefer to different objects at first glancethe use of dot notation may seem cumbersome on the other handwhen one imports module one often has no idea what local names might have been used in the implementation of that module the use of dot notation to fully qualify names avoids the possibility of getting burned by an accidental name clash for examplethe assignment statement pi does not change the value of pi used within the circle module there is variant of the import statement that allows the importing program to omit the module name when accessing names defined inside the imported module executing the statement from import creates bindings in the current scope to all objects defined within mbut not to itself for examplethe code from circle import print pi print circle pi superficiallythis may seem unrelated to the use of dot notation in method invocation howeveras we will see in there is deep connection |
4,032 | will first print and then produce the error message nameerrorname 'circleis not defined some python programmers frown upon using this form of import because they believe that it makes code more difficult to read as we have seena module can contain executable statements as well as function definitions typicallythese statements are used to initialize the module for this reasonthe statements in module are executed only the first time module is imported into program on related notea module is imported only once per interpreter session if you start up idleimport moduleand then change the contents of that modulethe interpreter will still be using the original version of the module this can lead to puzzling behavior when debugging you can force the interpreter to reload all imported modules by executing reload(there are lots of useful modules that come as part of the standard python library for exampleit is rarely necessary to write your own implementations of common mathematical or string functions description of this library can be found at files every computer system uses files to save things from one computation to the next python provides many facilities for creating and accessing files here we illustrate some of the basic ones each operating system ( windows and mac oscomes with its own file system for creating and accessing files python achieves operating-system independence by accessing files through something called file handle the code namehandle open('kids'' 'instructs the operating system to create file with the name kidsand return file handle for that file the argument 'wto open indicates that the file is to be opened for writing the following code opens fileuses the write method to write two linesand then closes the file it is important to remember to close the file when the program is finished using it otherwise there is risk that some or all of the writes may not be saved namehandle open('kids'' 'for in range( )name raw_input('enter name'namehandle write(name '\ 'namehandle close(in stringthe character "\is an escape character used to indicate that the next character should be treated in special way in this examplethe string '\nindicates new line character |
4,033 | functionsscopingand abstraction we can now open the file for reading (using the argument ' ')and print its contents since python treats file as sequence of lineswe can use for statement to iterate over the file' contents namehandle open('kids'' 'for line in namehandleprint line namehandle close(if we had typed in the names david and andreathis will print david andrea the extra line between david and andrea is there because print starts new line each time it encounters the '\nat the end of each line in the file we could have avoided printing that by writing print line[:- now consider namehandle open('kids'' 'namehandle write('michael\ 'namehandle write('mark\ 'namehandle close(namehandle open('kids'' 'for line in namehandleprint line[:- namehandle close(it will print michael mark notice that we have overwritten the previous contents of the file kids if we don' want to do that we can open the file for appending (instead of writingby using the argument 'afor exampleif we now run the code namehandle open('kids'' 'namehandle write('david\ 'namehandle write('andrea\ 'namehandle close(namehandle open('kids'' 'for line in namehandleprint line[:- namehandle close(it will print michael mark david andrea |
4,034 | some of the common operations on files are summarized in figure open(fn' 'fn is string representing file name creates file for writing and returns file handle open(fn' 'fn is string representing file name opens an existing file for reading and returns file handle open(fn' 'fn is string representing file name opens an existing file for appending and returns file handle fh read(returns string containing the contents of the file associated with the file handle fh fh readline(returns the next line in the file associated with the file handle fh fh readlines(returns list each element of which is one line of the file associated with the file handle fh fh write(swrite the string to the end of the file associated with the file handle fh fh writelines(ss is sequence of strings writes each element of to the file associated with the file handle fh fh close(closes the file associated with the file handle fh figure common functions for accessing files |
4,035 | the programs we have looked at thus far have dealt with three types of objectsintfloatand str the numeric types int and float are scalar types that is to sayobjects without accessible internal structure in contraststr can be thought of as structuredor non-scalartype one can use indexing to extract individual characters from string and slicing to extract substrings in this we introduce three structured types onetupleis rather simple generalization of str the other twolist and dictare more interesting--in part because they are mutable we also return to the topic of functions with some examples that illustrate the utility of being able to treat functions in the same way as other types of objects tuples like stringstuples are ordered sequences of elements the difference is that the elements of tuple need not be characters the individual elements can be of any typeand need not be of the same type as each other literals of type tuple are written by enclosing comma-separated list of elements within parentheses for examplewe can write ( ( 'two' print print unsurprisinglythe print statements produce the output (( 'two' looking at this exampleyou might naturally be led to believe that the tuple containing the single value would be written ( butto quote richard nixon"that would be wrong since parentheses are used to group expressions( is merely verbose way to write the integer to denote the singleton tuple containing this valuewe write ( ,almost everybody who uses python has at one time or another accidentally omitted that annoying comma like stringstuples can be concatenatedindexedand sliced consider ( 'two' ( print print ( print ( )[ print ( )[ : the second assignment statement binds the name to tuple that contains the tuple to which is bound and the floating point number this is |
4,036 | possible because tuplelike everything else in pythonis an objectso tuples can contain tuples thereforethe first print statement produces the output(( 'two' ) the second print statement prints the value generated by concatenating the values bound to and which is tuple with five elements it produces the output ( 'two' ( 'two' ) the next statement selects and prints the fourth element of the concatenated tuple (as always in pythonindexing starts at )and the statement after that creates and prints slice of that tupleproducing the output ( 'two' ( ( 'two' ) for statement can be used to iterate over the elements of tuple for examplethe following code prints the common divisors of and and then the sum of all the divisors def finddivisors ( )"""assumes that and are positive ints returns tuple containing all common divisors of ""divisors (#the empty tuple for in range( min ( )if % = and % = divisors divisors ( ,return divisors divisors finddivisors( print divisors total for in divisorstotal + print total sequences and multiple assignment if you know the length of sequence ( tuple or string)it can be convenient to use python' multiple assignment statement to extract the individual elements for exampleafter executing the statement xy ( ) will be bound to and to similarlythe statement abc 'xyzwill bind to ' ' to ' 'and to 'zthis mechanism is particularly convenient when used in conjunction with functions that return fixed-size sequences |
4,037 | structured typesmutabilityand higher-order functions considerfor example the function def findextremedivisors( )"""assumes that and are positive ints returns tuple containing the smallest common divisor and the largest common divisor of and ""divisors (#the empty tuple minvalmaxval nonenone for in range( min( )if % = and % = if minval =none or minvalminval if maxval =none or maxvalmaxval return (minvalmaxvalthe multiple assignment statement mindivisormaxdivisor findextremedivisors( will bind mindivisor to and maxdivisor to lists and mutability like tuplea list is an ordered sequence of valueswhere each value is identified by an index the syntax for expressing literals of type list is similar to that used for tuplesthe difference is that we use square brackets rather than parentheses the empty list is written as []and singleton lists are written without that (oh so easy to forgetcomma before the closing bracket sofor examplethe codel [' did it all' 'love'for in range(len( ))print [iproduces the outputi did it all love occasionallythe fact that square brackets are used for literals of type listindexing into listsand slicing lists can lead to some visual confusion for examplethe expression [ , , , ][ : ][ ]which evaluates to uses the square brackets in three different ways this is rarely problem in practicebecause most of the time lists are built incrementally rather than written as literals lists differ from tuples in one hugely important waylists are mutable in contrasttuples and strings are immutable there are many operators that can be used to create objects of these immutable typesand variables can be bound to objects of these types but objects of immutable types cannot be modified on the other handobjects of type list can be modified after they are created the distinction between mutating an object and assigning an object to variable mayat firstappear subtle howeverif you keep repeating the mantra"in |
4,038 | python variable is merely namei label that can be attached to an object,it will bring you clarity when the statements techs ['mit''caltech'ivys ['harvard''yale''brown'are executedthe interpreter creates two new lists and binds the appropriate variables to themas pictured below figure two lists the assignment statements univs [techsivysunivs [['mit''caltech']['harvard''yale''brown']also create new lists and bind variables to them the elements of these lists are themselves lists the three print statements print 'univs ='univs print 'univs ='univs print univs =univs produce the output univs [['mit''caltech']['harvard''yale''brown']univs [['mit''caltech']['harvard''yale''brown']true it appears as if univs and univs are bound to the same value but appearances can be deceiving as the following picture illustratesunivs and univs are bound to quite different values |
4,039 | structured typesmutabilityand higher-order functions figure two lists that appear to have the same valuebut don' that univs and univs are bound to different objects can be verified using the built-in python function idwhich returns unique integer identifier for an object this function allows us to test for object equality when we run the code print univs =univs #test value equality print id(univs=id(univs #test object equality print 'id of univs ='id(univsprint 'id of univs ='id(univs it prints true false id of univs id of univs (don' expect to see the same unique identifiers if you run this code the semantics of python says nothing about what identifier is associated with each objectit merely requires that no two objects have the same identifier notice that in figure the elements of univs are not copies of the lists to which techs and ivys are boundbut are rather the lists themselves the elements of univs are lists that contain the same elements as the lists in univsbut they are not the same lists we can see this by running the code print 'ids of univs[ and univs[ ]'id(univs[ ])id(univs[ ]print 'ids of univs [ and univs [ ]'id(univs [ ])id(univs [ ]which prints ids of univs[ and univs[ ids of univs [ and univs [ why does this matterit matters because lists are mutable consider the code techs append('rpi' |
4,040 | the append method has side effect rather than create new listit mutates the existing list techs by adding new elementthe string 'rpi'to the end of it after append is executedthe state of the computation looks like figure demonstration of mutability univs still contains the same two listsbut the contents of one of those lists has been changed consequentlythe print statements print 'univs ='univs print 'univs ='univs now produce the output univs [['mit''caltech''rpi']['harvard''yale''brown']univs [['mit''caltech']['harvard''yale''brown']what we have here is something called aliasing there are two distinct paths to the same list object one path is through the variable techs and the other through the first element of the list object to which univs is bound one can mutate the object via either pathand the effect of the mutation will be visible through both paths this can be convenientbut it can also be treacherous unintentional aliasing leads to programming errors that are often enormously hard to track down as with tuplesa for statement can be used to iterate over the elements of list for examplefor in univsprint 'univs contains' print which containsfor in eprint ' |
4,041 | structured typesmutabilityand higher-order functions will print univs contains ['mit''caltech''rpi'which contains mit caltech rpi univs contains ['harvard''yale''brown'which contains harvard yale brown when we append one list to anothere techs append(ivys)the original structure is maintained the result is list that contains list suppose we do not want to maintain this structurebut want to add the elements of one list into another list we can do that by using list concatenation or the extend methode [ , , [ , , print ' =' extend( print ' =' append( print ' =' will print [ [ [ [ ]notice that the operator does not have side effect it creates new list and returns it in contrastextend and append each mutated figure contains short descriptions of some of the methods associated with lists note that all of these except count and index mutate the list append(eadds the object to the end of count(ereturns the number of times that occurs in insert(ieinserts the object into at index extend( adds the items in list to the end of remove(edeletes the first occurrence of from index(ereturns the index of the first occurrence of in it raises an exception (see if is not in pop(iremoves and returns the item at index in if is omittedit defaults to - to remove and return the last element of sort(sorts the elements of in ascending order reverse(reverses the order of the elements in figure methods associated with lists |
4,042 | cloning though allowedit is usually prudent to avoid mutating list over which one is iterating considerfor examplethe code def removedups( )"""assumes that and are lists removes any element from that also occurs in ""for in if in remove( [ , , , [ , , , removedups( print ' =' you might be surprised to discover that the print statement produces the output [ during for loopthe implementation of python keeps track of where it is in the list using an internal counter that is incremented at the end of each iteration when the value of the counter reaches the current length of the listthe loop terminates this works as one might expect if the list is not mutated within the loopbut can have surprising consequences if the list is mutated in this casethe hidden counter starts out at discovers that [ is in and removes it--reducing the length of to the counter is then incremented to and the code proceeds to check if the value of [ is in notice that this is not the original value of [ ( )but rather the current value of [ ( as you can seeit is possible to figure out what happens when the list is modified within the loop howeverit is not easy and what happens is likely to be unintentionalas in this example one way to avoid this kind of problem is to use slicing to clone ( make copy ofthe list and write for in [:notice that writing newl followed by for in newl would not have solved the problem it would not have created copy of but would merely have introduced new name for the existing list slicing is not the only way to clone lists in python the expression list(lreturns copy of the list if the list to be copied contains mutable objects that you want to copy as wellimport the standard library module copy and use the function copy deepcopy list comprehension list comprehension provides concise way to apply an operation to the values in sequence it creates new list in which each element is the result of applying given operation to value from sequence ( the elements in another listfor examplel [ ** for in range( , )print |
4,043 | structured typesmutabilityand higher-order functions will print the list [ the for clause in list comprehension can be followed by one or more if and for statements that are applied to the values produced by the for clause these additional clauses modify the sequence of values generated by the first for clause and produce new sequence of valuesto which the operation associated with the comprehension is applied for examplethe code mixed [ ' ' print [ ** for in mixed if type( =intsquares the integers in mixedand then prints [ some python programmers use list comprehensions in marvelous and subtle ways that is not always great idea remember that somebody else may need to read your codeand "subtleis not usually desirable property functions as objects in pythonfunctions are first-class objects that means that they can be treated like objects of any other typee int or list they have typese the expression type(facthas the value they can appear in expressionse as the right-hand side of an assignment statement or as an argument to functionthey can be elements of listsetc using functions as arguments can be particularly convenient in conjunction with lists it allows style of coding called higher-order programming consider the code in figure def applytoeach(lf)"""assumes is listf function mutates by replacing each elementeof by ( )""for in range(len( )) [if( [ ] [ - print ' =' print 'apply abs to each element of applytoeach(labsprint ' =' print 'apply int to each element of' applytoeach(lintprint ' =' print 'apply factorial to each element of' applytoeach(lfactrprint ' =' print 'apply fibonnaci to each element of' applytoeach(lfibprint ' =' figure applying function to elements of list |
4,044 | the function applytoeach is called higher-order because it has an argument that is itself function the first time it is calledit mutates by applying the unary built-in function abs to each element the second time it is calledit applies type conversion to each element the third time it is calledit replaces each element by the result of applying the function factr (defined in figure to each element and the fourth time it is calledit replaces each element by the result of applying the function fib (defined in figure to each element it prints [ - apply abs to each element of [ apply int to each element of [ [ apply factorial to each element of [ [ apply fibonnaci to each element of [ [ python has built-in higher-order functionmapthat is similar tobut more general thanthe applytoeach function defined in figure in its simplest form the first argument to map is unary function ( function that has only one parameterand the second argument is any ordered collection of values suitable as arguments to the first argument it returns list generated by applying the first argument to each element of the second argument for examplethe expression map(fact[ ]has the value [ more generallythe first argument to map can be of function of argumentsin which case it must be followed by subsequent ordered collections for examplethe code [ [ print map(minl prints the list [ |
4,045 | structured typesmutabilityand higher-order functions stringstuplesand lists we have looked at three different sequence typesstrtupleand list they are similar in that objects of all of these types can be operated upon as described in figure seq[ireturns the ith element in the sequence len(seqreturns the length of the sequence seq seq returns the concatenation of the two sequences seq returns sequence that repeats seq times seq[start:endreturns slice of the sequence in seq is true if is contained in the sequence and false otherwise not in seq is true if is not in the sequence and false otherwise for in seq iterates over the elements of the sequence figure common operations on sequence types some of their other similarities and differences are summarized in figure type type of elements examples of literals mutable str characters ''' ''abcno tuple any type ()( ,)('abc' no list any type [][ ]['abc' yes figure comparison of sequence types python programmers tend to use lists far more often than tuples since lists are mutablethey can be constructed incrementally during computation for examplethe following code incrementally builds list containing all of the even numbers in another list evenelems [for in lif % = evenelems append(eone advantage of tuples is that because they are immutablealiasing is never worry another advantage of their being immutable is that tuplesunlike listscan be used as keys in dictionariesas we will see in the next section since strings can contain only charactersthey are considerably less versatile than tuples or lists on the other handwhen you are working with string of characters there are many built-in methods that make life easy figure contains short descriptions of few of them keep in mind that since strings are immutable these all return values and have no side effect |
4,046 | count( counts how many times the string occurs in find( returns the index of the first occurrence of the substring in sand - if is not in rfind( same as findbut starts from the end of (the "rin rfind stands for reverses index( same as findbut raises an exception (see if is not in rindex( same as indexbut starts from the end of lower(converts all uppercase letters in to lowercase replace(oldnewreplaces all occurrences of the string old in with the string new rstrip(removes trailing white space from split(dsplits using as delimiter returns list of substrings of for examplethe value of 'david guttag plays basketballsplit('is ['david''guttag''plays''basketball'if is omittedthe substrings are separated by arbitrary strings of whitespace characters (spacetabnewlinereturnand formfeedfigure some methods on strings dictionaries objects of type dict (short for dictionaryare like lists except that "indicesneed not be integers--they can be values of any immutable type since they are not orderedwe call them keys rather than indices think of dictionary as set of key/value pairs literals of type dict are enclosed in curly bracesand each element is written as key followed by colon followed by value for examplethe codemonthnumbers {'jan': 'feb': 'mar': 'apr': 'may': :'jan' :'feb' :'mar' :'apr' :'may'print 'the third month is monthnumbers[ dist monthnumbers['apr'monthnumbers['jan'print 'apr and jan are'dist'months apartwill print the third month is mar apr and jan are months apart the entries in dict are unordered and cannot be accessed with an index that' why monthnumbers[ unambiguously refers to the entry with the key rather than the second entry the method keys returns list containing the keys of dictionary the order in which the keys appear is not defined sofor examplethe code print monthnumbers keys(might print [ 'mar''feb' 'apr''jan''may' |
4,047 | structured typesmutabilityand higher-order functions when for statement is used to iterate over dictionarythe value assigned to the iteration variable is keynot key/value pair for examplethe code keys [for in monthnumberskeys append(ekeys sort(print keys prints [ 'apr''feb''jan''mar''may'dictionaries are one of the great things about python they greatly reduce the difficulty of writing variety of programs for examplein figure we use dictionaries to write (pretty horribleprogram to translate between languages etof {'bread':'pain''wine':'vin''with':'avec'' ':'je''eat':'mange''drink':'bois''john':'jean''friends':'amis''and''et''of':'du','red':'rouge'ftoe {'pain':'bread''vin':'wine''avec':'with''je':' ''mange':'eat''bois':'drink''jean':'john''amis':'friends''et':'and''du':'of''rouge':'red'dicts {'english to french':etof'french to english':ftoedef translateword(worddictionary)if word in dictionary keys()return dictionary[wordelif word !''return '"word '"return word def translate(phrasedictsdirection)ucletters 'abcdefghijklmnopqrstuvwxyzlcletters 'abcdefghijklmnopqrstuvwxyzletters ucletters lcletters dictionary dicts[directiontranslation 'word 'for in phraseif in lettersword word elsetranslation translationtranslateword(worddictionaryc word 'return translation translateword(worddictionaryprint translate(' drink good red wineand eat bread 'dicts,'english to french'print translate('je bois du vin rouge 'dicts'french to english'figure translating text (badlythe code in the figure printsje bois "goodrouge vinet mange pain drink of wine red like listsdictionaries are mutable soone must be careful about side effects for example |
4,048 | ftoe['bois''woodprint translate('je bois du vin rouge 'dicts'french to english'will print wood of wine red we add elements to dictionary by assigning value to an unused keye ftoe['blanc''whiteas with liststhere are many useful methodsincluding some for removing elementsassociated with dictionaries we do not enumerate them herebut will use them as convenient in examples later in the book figure contains some of the more useful operations on dictionaries len(dreturns the number of items in keys(returns list containing the keys in values(returns list containing the values in in returns true if key is in [kreturns the item in with key get(kvreturns [kif is in dand otherwise [kv associates the value with the key in if there is already value associated with kthat value is replaced del [kremoves the key from for in iterates over the keys in figure some common operations on dicts objects of any immutable typee type tuplemay be used as dictionary keys imagine for example using tuple of the form (flightnumberdayto represent airline flights it would then be easy to use such tuples as keys in dictionary implementing mapping from flights to arrival times most programming languages do not contain built-in type that provides mapping from keys to values insteadprogrammers use other types to provide similar functionality it isfor examplerelatively easy to implement dictionary using list in which each element is key/value pair one can then write simple function that does the associative retrievale def keysearch(lk)for elem in lif elem[ =kreturn elem[ return none the problem with such an implementation is that it is computationally inefficient in the worst casea program might have to examine each element in the list to perform single retrieval in contrastthe built-in implementation is quite fast it uses technique called hashingdescribed in to do the lookup in time that is nearly independent of the size of the dictionary |
4,049 | we hate to bring this upbut dr pangloss was wrong we do not live in "the best of all possible worlds there are some places where it rains too littleand others where it rains too much some places are too coldsome too hotand some too hot in the summer and too cold in the winter sometimes the stock market goes down-- lot andperhaps worst of allour programs don' always function properly the first time we run them books have been written about how to deal with this last problemand there is lot to be learned from reading these books howeverin the interest of providing you with some hints that might help you get that next problem set in on timethis provides highly condensed discussion of the topic while all of the programming examples are in pythonthe general principles are applicable to getting any complex system to work testing is the process of running program to try and ascertain whether or not it works as intended debugging is the process of trying to fix program that you already know does not work as intended testing and debugging are not processes that you should begin to think about after program has been built good programmers design their programs in ways that make them easier to test and debug the key to doing this is breaking the program up into separate components that can be implementedtestedand debugged independently of other components at this point in the bookwe have discussed only one mechanism for modularizing programsthe function sofor nowall of our examples will be based around functions when we get to other mechanismsin particular classeswe will return to some of the topics covered in this the first step in getting program to work is getting the language system to agree to run it--that iseliminating syntax errors and static semantic errors that can be detected without running the program if you haven' gotten past that point in your programmingyou're not ready for this spend bit more time working on small programsand then come back testing the most important thing to say about testing is that its purpose is to show that bugs existnot to show that program is bug-free to quote edsger dijkstra"program testing can be used to show the presence of bugsbut never to show their absence!" oras albert einstein reputedly once said"no amount of experimentation can ever prove me righta single experiment can prove me wrong "notes on structured programming,technical university eindhovent report wsk- april |
4,050 | why is this soeven the simplest of programs has billions of possible inputs considerfor examplea program that purports to meet the specificationdef isbigger(xy)"""assumes and are ints returns true if is less than and false otherwise ""running it on all pairs of integers would beto say the leasttedious the best we can do is to run it on pairs of integers that have reasonable probability of producing the wrong answer if there is bug in the program the key to testing is finding collection of inputscalled test suitethat has high likelihood of revealing bugsyet does not take too long to run the key to doing this is partitioning the space of all possible inputs into subsets that provide equivalent information about the correctness of the programand then constructing test suite that contains one input from each partition (usuallyconstructing such test suite is not actually possible think of this as an unachievable ideal partition of set divides that set into collection of subsets such that each element of the original set belongs to exactly one of the subsets considerfor exampleisbigger(xythe set of possible inputs is all pairwise combinations of integers one way to partition this set is into these seven subsetsx positivey positive negativey negative positivey negative negativey positive if one tested the implementation on at least one value from each of these subsetsthere would be reasonable probability (but no guaranteeof exposing bug if one exists for most programsfinding good partitioning of the inputs is far easier said than done typicallypeople rely on heuristics based on exploring different paths through some combination of the code and the specifications heuristics based on exploring paths through the code fall into class called glass-box testing heuristics based on exploring paths through the specification fall into class called black-box testing black-box testing in principleblack-box tests are constructed without looking at the code to be tested black-box testing allows testers and implementers to be drawn from separate populations when those of us who teach programming courses generate test cases for the problem sets we assign studentswe are developing black-box test suites developers of commercial software often have quality assurance groups that are largely independent of development groups |
4,051 | testing and debugging this independence reduces the likelihood of generating test suites that exhibit mistakes that are correlated with mistakes in the code supposefor examplethat the author of program made the implicitbut invalidassumption that function would never be called with negative number if the same person constructed the test suite for the programhe would likely repeat the mistakeand not test the function with negative argument another positive feature of black-box testing is that it is robust with respect to implementation changes since the test data is generated without knowledge of the implementationit need not be changed when the implementation is changed as we said earliera good way to generate black-box test data is to explore paths through specification considerthe specification def sqrt(xepsilon)"""assumes xepsilon floats > epsilon returns result such that -epsilon <result*result < +epsilon""there seem to be only two distinct paths through this specificationone corresponding to and one corresponding to howevercommon sense tells us that while it is necessary to test these two casesit is hardly sufficient boundary conditions should also be tested when looking at liststhis often means looking at the empty lista list with exactly one elementand list containing lists when dealing with numbersit typically means looking at very small and very large values as well as "typicalvalues for sqrtit might make sense to try values of and epsilon similar to those in the following table the first four rows are intended to represent typical cases notice that the values for include perfect squarea number less than oneand number with an irrational square root if any of these tests failthere is bug in the program that needs to be fixed the remaining rows test extremely large and small values of and epsilon if any of these tests failsomething needs to be fixed perhaps there is bug in the code that needs to be fixedor perhaps the specification needs to be changed so that it is easier to meet it mightfor examplebe unreasonable to expect to find an approximation of square root when epsilon is ridiculously small epsilon ** ** ** ** ** ** ** ** ** |
4,052 | another important boundary condition to think about is aliasing considerfor examplethe code def copy( )"""assumes are lists mutates to be copy of ""while len( #remove all elements from pop(#remove last element of for in #append ' elements to initially empty append(eit will work most of the timebut not when and refer to the same list any test suite that did not include call of the form copy(ll)would not reveal the bug glass-box testing black-box testing should never be skippedbut it is rarely sufficient without looking at the internal structure of the codeit is impossible to know which test cases are likely to provide new information consider the following trivial exampledef isprime( )"""assumes is nonnegative int returns true if is primefalse otherwise""if < return false for in range( )if % = return false return true looking at the codewe can see that because of the test if < the values and are treated as special casesand therefore need to be tested without looking at the codeone might not test isprime( )and would therefore not discover that the function call isprime( returns falseerroneously indicating that is not prime glass-box test suites are usually much easier to construct than black-box test suites specifications are usually incomplete and often pretty sloppymaking it challenge to estimate how thoroughly black-box test suite explores the space of interesting inputs in contrastthe notion of path through code is well definedand it is relatively easy to evaluate how thoroughly one is exploring the space there arein factcommercial tools that can be used to objectively measure the completeness of glass-box tests glass-box test suite is path-complete if it exercises every potential path through the program this is typically impossible to achievebecause it depends upon the number of times each loop is executed and the depth of each recursion for examplea recursive implementation of factorial follows different path for each possible input (because the number of levels of recursion will differ |
4,053 | testing and debugging furthermoreeven path-complete test suite does not guarantee that all bugs will be exposed considerdef abs( )"""assumes is an int returns if >= and - otherwise""if - return - elsereturn the specification suggests that there are two possible casesx is either negative or it isn' this suggests that the set of inputs { - is sufficient to explore all paths in the specification this test suite has the additional nice property of forcing the program through all of its pathsso it looks like complete glass-box suite as well the only problem is that this test suite will not expose the fact that abs(- )will return - despite the limitations of glass-box testingthere are few rules of thumb that are usually worth followingexercise both branches of all if statements make sure that each except clause (see is executed for each for loophave test cases in which the loop is not entered ( if the loop is iterating over the elements of listmake sure that it is tested on the empty list) the body of the loop is executed exactly onceand the body of the loop is executed more than once for each while loopo look at the same kinds of cases as when dealing with for loopsand include test cases corresponding to all possible ways of exiting the loop for examplefor loop starting with while len( and not [ = find cases where the loop exits because len(lis greater than zero and cases where it exits because [ = for recursive functionsinclude test cases that cause the function to return with no recursive callsexactly one recursive calland more than one recursive call conducting tests testing is often thought of as occurring in two phases one should always start with unit testing during this phase testers construct and run tests designed to ascertain whether individual units of code ( functionswork properly this is followed by integration testingwhich is designed to ascertain whether the program as whole behaves as intended in practicetesters cycle through |
4,054 | these two phasessince failures during integration testing lead to making changes to individual units integration testing is almost always more challenging than unit testing one reason for this is that the intended behavior of an entire program is often considerably harder to characterize than the intended behavior of each of its parts for examplecharacterizing the intended behavior of word processor is considerably more challenging than characterizing the behavior of function that counts the number of characters in document problems of scale can also make integration testing difficult it is not unusual for integration tests to take hours or even days to run many industrial software development organizations have software quality assurance (sqagroup that is separate from the group charged with implementing the software the mission of this group is to insure that before the software is released it is suitable for its intended purpose in some organizations the development group is responsible for unit testing and the qa group for integration testing in industrythe testing process is often highly automated testers do not sit at terminals typing inputs and checking outputs insteadthey use test drivers that autonomously set up the environment needed to invoke the program (or unitto be testedinvoke the program (or unitto be tested with predefined or automatically generated sequence of inputssave the results of these invocationscheck the acceptability of the results of the testsand prepare an appropriate report during unit testingwe often need to build stubs as well as drivers drivers simulate parts of the program that use the unit being testedwhereas stubs simulate parts of the program used by the unit being tested stubs are useful because they allow people to test units that depend upon software or sometimes even hardware that does not yet exist this allows teams of programmers to simultaneously develop and test multiple parts of system ideallya stub should check the reasonableness of the environment and arguments supplied by the caller (calling function with inappropriate arguments is common error)modify arguments and global variables in manner consistent with the specificationand return values consistent with the specification orfor that matterthose who grade problem sets in very large programming courses |
4,055 | testing and debugging building adequate stubs is often challenge if the unit the stub is replacing is intended to perform some complex taskbuilding stub that performs actions consistent with the specification may be tantamount to writing the program that the stub is designed to replace one way to surmount this problem is to limit the set of arguments accepted by the stuband create table that contains the values to be returned for each combination of arguments to be used in the test suite one attraction of automating the testing process is that it facilitates regression testing as programmers attempt to debug programit is all too common to install "fixthat breaks something that used to work whenever any change is madeno matter how smallyou should check that the program still passes all of the tests that it used to pass debugging there is charming urban legend about how the process of fixing flaws in software came to be known as debugging the photo below is of september page in laboratory book from the group working on the mark ii aiken relay calculator at harvard university some have claimed that the discovery of that unfortunate moth trapped in the mark ii led to the use of the phrase debugging however the wording"first actual case of bug being found,suggests that less literal interpretation of the phrase was already common grace murray hoppera leader of the mark ii projectmade it clear that the term "bugwas already in wide use to describe problems with electronic systems during world war ii and well prior to thathawkinsnew catechism of electricityan electrical handbookincluded the entry"the term 'bugis used to limited extent to designate any fault or trouble in the connections or working of electric apparatus in english usage the word "bugbearmeans "anything causing seemingly needless or excessive |
4,056 | fear or anxiety " shakespeare seems to have shortened this to "bug,when he had hamlet kvetch about "bugs and goblins in my life " the use of the word "bugsometimes leads people to ignore the fundamental fact that if you wrote program and it has "bug,you messed up bugs do not crawl unbidden into flawless programs if your program has bugit is because you put it there bugs do not breed in programs if your program has multiple bugsit is because you made multiple mistakes runtime bugs can be categorized along two dimensions overt covertan overt bug has an obvious manifestatione the program crashes or takes far longer (maybe foreverto run than it should covert bug has no obvious manifestation the program may run to conclusion with no problem--other than providing an incorrect answer many bugs fall between the two extremesand whether or not the bug is overt can depend upon how carefully one examines the behavior of the program persistent intermittenta persistent bug occurs every time the program is run with the same inputs an intermittent bug occurs only some of the timeeven when the program is run on the same inputs and seemingly under the same conditions when we get to we will start writing programs of the kind where intermittent bugs are common the best kinds of bugs to have are overt and persistent developers can be under no illusion about the advisability of deploying the program and if someone else is foolish enough to attempt to use itthey will quickly discover their folly perhaps the program will do something horrible before crashinge delete filesbut at least the user will have reason to be worried (if not panickedgood programmers try to write their programs in such way that programming mistakes lead to bugs that are both overt and persistent this is often called defensive programming the next step into the pit of undesirability is bugs that are overt but intermittent an air traffic control system that computes the correct location for planes almost all of the time would be far more dangerous than one that makes obvious mistakes all the time one can live in fool' paradise for period of timeand maybe get so far are as deploying system incorporating the flawed programbut sooner or later the bug will become manifest if the conditions prompting the bug to become manifest are easily reproducibleit is often relatively easy to track down and repair the problem if the conditions provoking the bug are not clearlife is much harder programs that fail in covert ways are often highly dangerous since they are not apparently problematicalpeople use them and trust them to do the right thing increasinglysociety relies on software to perform critical computations that are beyond the ability of humans to carry out or even check for correctness webster' new world college dictionary act scene |
4,057 | testing and debugging thereforea program can provide undetected fallacious answer for long periods of time such programs canand havecaused lot of damage program that evaluates the risk of mortgage bond portfolio and confidently spits out the wrong answer can get bank (and perhaps all of societyinto lot of trouble radiation therapy machine that delivers little more or little less radiation than intended can be the difference between life and death for person with cancer program that makes covert error only occasionally may or may not wreak less havoc than one that always commits such an error bugs that are both covert and intermittent are almost always the hardest to find and fix learning to debug debugging is learned skill nobody does it well instinctively the good news is that it' not hard to learnand it is transferable skill the same skills used to debug software can be used to find out what is wrong with other complex systemse laboratory experiments or sick humans for at least four decades people have been building tools called debuggersand there are debugging tools built into idle these are supposed to help people find bugs in their programs they can helpbut only little what' much more important is how you approach the problem many experienced programmers don' even bother with debugging tools most programmers say that the most important debugging tool is the print statement debugging starts when testing has demonstrated that the program behaves in undesirable ways debugging is the process of searching for an explanation of that behavior the key to being consistently good at debugging is being systematic in conducting that search start by studying the available data this includes the test results and the program text study all of the test results examine not only the tests that revealed the presence of problembut also those tests that seemed to work perfectly trying to understand why one test worked and another did not is often illuminating when looking at the program textkeep in mind that you don' completely understand it if you didthere probably wouldn' be bug nextform hypothesis that you believe to be consistent with all the data the hypothesis could be as narrow as "if change line from to <ythe problem will go awayor as broad as "my program is not terminating because have the wrong exit condition in some while loop nextdesign and run repeatable experiment with the potential to refute the hypothesis for exampleyou might put print statement before and after each while loop if these are always pairedthen the hypothesis that while loop is causing nontermination has been refuted decide before running the experiment how you would interpret various possible results if you wait until on august knight capital groupinc deployed new piece of stock-trading software within forty-five minutes bug in that software lost the company $ , , the next daythe ceo of knight commented that the bug caused the software to enter " ton of ordersall erroneous |
4,058 | testing and debugging after you run the experimentyou are more likely to fall prey to wishful thinking finallyit' important to keep record of what experiments you have tried when you've spent many hours changing your code trying to track down an elusive bugit' easy to forget what you have already tried if you aren' carefulit is easy to waste way too many hours trying the same experiment (or more likely an experiment that looks different but will give you the same informationover and over again rememberas many have said"insanity is doing the same thingover and over againbut expecting different results " designing the experiment think of debugging as search processand each experiment as an attempt to reduce the size of the search space one way to reduce the size of the search space is to design an experiment that can be used to decide whether specific region of code is responsible for problem uncovered during integration testing another way to reduce the search space is to reduce the amount of test data needed to provoke manifestation of bug let' look at contrived example to see how one might go about debugging it imagine that you wrote the palindrome checking code in figure and that you are so confident of your programming skills that you put it up on the web-without testing it suppose further that you receive an email saying" tested your !!**program on the following -string inputand it printed yes yet any fool can see that it is not palindrome fix it!def ispal( )"""assumes is list returns true if the list is palindromefalse otherwise""temp temp reverse if temp =xreturn true elsereturn false def silly( )"""assumes is an int gets inputs from user prints 'yesif the sequence of inputs forms palindrome'nootherwise""for in range( )result [elem raw_input('enter element'result append(elemif ispal(result)print 'yeselseprint 'nofigure program with bugs this line appears in rita mae brown'ssudden death howeverit has been variously attributed to many other sources--including albert einstein |
4,059 | testing and debugging you could try and test it on the supplied -string input but it might be more sensible to begin by trying it on something smaller in factit would make sense to test it on minimal non-palindromee silly( enter elementa enter elementb the good news is that it fails even this simple testso you don' have to type in thousand strings the bad news is that you have no idea why it failed in this casethe code is small enough that you can probably stare at it and find the bug (or bugshoweverlet' pretend that it is too large to do thisand start to systematically reduce the search space often the best way to do this is to conduct binary search find some point about halfway through the codeand devise an experiment that will allow you to decide if there is problem before that point that might be related to the symptom (of coursethere may be problems after that point as wellbut it is usually best to hunt down one problem at time in choosing such pointlook for place where there are some easily examined intermediate values that provide useful information if an intermediate value is not what you expectedthere is probably problem that occurred prior to that point in the code if the intermediate values all look finethe bug probably lies somewhere later in the code this process can be repeated until you have narrowed the region in which problem is located to few lines of code looking at sillythe halfway point is around the line if ispal(resultthe obvious thing to check is whether result has the expected value[' '' 'we check this by inserting the statement print result before the if statement in silly when the experiment is runthe program prints [' ']suggesting that something has already gone wrong the next step is to print result roughly halfway through the loop this quickly reveals that result is never more than one element longsuggesting that the initialization of result needs to be moved outside the for loop the corrected code for silly is def silly( )"""assumes is an int gets inputs from user prints 'yesif the sequence of inputs forms palindrome'nootherwise""result [for in range( )elem raw_input('enter element'result append(elemprint result if ispal(result)print 'yeselseprint 'nolet' try thatand see if result has the correct value after the for loop it doesbut unfortunately the program still prints yes nowwe have reason to believe that second bug lies below the print statement solet' look at ispal the line if temp =xis about halfway through that function sowe insert the |
4,060 | line print tempx before that line when we run the codewe see that temp has the expected valuebut does not moving up the codewe insert print statement after the line temp xand discover that both temp and have the value [' '' ' quick inspection of the code reveals that in ispal we wrote temp reverse rather than temp reverse()--the evaluation of temp reverse returns the built-in reverse method for listsbut does not invoke it we run the test againand now it seems that both temp and have the value [' '' 'we have now narrowed the bug to one line it seems that temp reverse(unexpectedly changed the value of an aliasing bug has bitten ustemp and are names for the same listboth before and after the list gets reversed one way to fix it is to replace the first assignment statement in ispal by temp [:]which causes copy of to be made the corrected version of ispal is def ispal( )"""assumes is list returns true if the list is palindromefalse otherwise""temp [:temp reverse(if temp =xreturn true elsereturn false when the going gets tough joseph kennedyfather of president kennedyreputedly instructed his children"when the going gets toughthe tough get going " but he never debugged piece of software this subsection contains few pragmatic hints about what do when the debugging gets tough look for the usual suspects have you passed arguments to function in the wrong ordero misspelled namee typed lowercase letter when you should have typed an uppercase oneo failed to reinitialize variableo tested that two floating point values are equal (==instead of nearly equal (remember that floating point arithmetic is not the same as the arithmetic you learned in school) tested for value equality ( compared two lists by writing the expression = when you meant object equality ( id( =id( )) forgotten that some built-in function has side effect one might well wonder why there isn' static checker that detected the fact that the line of code temp reverse doesn' cause any useful computatation to be doneand is therefore likely to be an error he also reputedly told jfk"don' buy single vote more than necessary 'll be damned if ' going to pay for landslide |
4,061 | testing and debugging forgotten the (that turns reference to an object of type function into function invocationo created an unintentional aliasor made any other mistake that is typical for you stop asking yourself why the program isn' doing what you want it to insteadask yourself why it is doing what it is that should be an easier question to answerand will probably be good first step in figuring out how to fix the program keep in mind that the bug is probably not where you think it is if it wereyou would probably have found it long ago one practical way to go about deciding where to look is asking where the bug cannot be as sherlock holmes said"eliminate all other factorsand the one which remains must be the truth " try to explain the problem to somebody else we all develop blind spots it is often the case that merely attempting to explain the problem to someone will lead you to see things you have missed good thing to try to explain is why the bug cannot be in certain places don' believe everything you read in particulardon' believe the documentation the code may not be doing what the comments suggest stop debugging and start writing documentation this will help you approach the problem from different perspective walk awayand try again tomorrow this may mean that bug is fixed later in time than if you had stuck with itbut you will probably spend lot less of your time looking for it that isit is possible to trade latency for efficiency (studentsthis is an excellent reason to start work on programming problem sets earlier rather than later!and when you have found "thebug when you think you have found bug in your codethe temptation to start coding and testing fix is almost irresistible it is often betterhoweverto slow down little remember that the goal is not to fix one bugbut to move rapidly and efficiently towards bug-free program ask yourself if this bug explains all the observed symptomsor whether it is just the tip of the iceberg if the latterit may be better to think about taking care of this bug in concert with other changes supposefor examplethat you have discovered that the bug is the result of having accidentally mutated list you could circumvent the problem locally (perhaps by making copy of the list)or you could consider using tuple instead of list (since tuples are immutable)perhaps eliminating similar bugs elsewhere in the code before making any changetry and understand the ramification of the proposed "fix will it break something elsedoes it introduce excessive complexitydoes it offer the opportunity to tidy up other parts of the code arthur conan doyle"the sign of the four |
4,062 | always make sure that you can get back to where you are there is nothing more frustrating than realizing that long series of changes have left you further from the goal than when you startedand having no way to get back to where you started disk space is usually plentiful use it to store old versions of your program finallyif there are many unexplained errorsyou might consider whether finding and fixing bugs one at time is even the right approach maybe you would be better off thinking about whether there is some better way to organize your program or some simpler algorithm that will be easier to implement correctly |
4,063 | an "exceptionis usually defined as "something that does not conform to the norm,and is therefore somewhat rare there is nothing rare about exceptions in python they are everywhere virtually every module in the standard python library uses themand python itself will raise them in many different circumstances you've already seen some of them open python shell and entertest [ , , test[ and the interpreter will respond with something like traceback (most recent call last)file ""line in test[ indexerrorlist index out of range indexerror is the type of exception that python raises when program tries to access an element that is not within the bounds of an indexable type the string following indexerror provides additional information about what caused the exception to occur most of the built-in exceptions of python deal with situations in which program has attempted to execute statement with no appropriate semantics (we will deal with the exceptional exceptions--those that do not deal with errors--later in this those readers (all of youwe hopewho have attempted to write and run python programs will already have encountered many of these among the most commonly occurring types of exceptions are typeerrornameerrorand valueerror handling exceptions up to nowwe have treated exceptions as fatal events when an exception is raisedthe program terminates (crashes might be more appropriate word in this case)and we go back to our code and attempt to figure out what went wrong when an exception is raised that causes the program to terminatewe say that an unhandled exception has been raised an exception does not need to lead to program termination exceptionswhen raisedcan and should be handled by the program sometimes an exception is raised because there is bug in the program (like accessing variable that doesn' exist)but many timesan exception is something the programmer can and should anticipate program might try to open file that does not exist if an interactive program asks user for inputthe user might enter something inappropriate |
4,064 | if you know that line of code might raise an exception when executedyou should handle the exception in well-written programunhandled exceptions should be the exception consider the code successfailureratio numsuccesses/float(numfailuresprint 'the success/failure ratio is'successfailureratio print 'now heremost of the timethis code will work just finebut it will fail if numfailures happens to be zero the attempt to divide by zero will cause the python runtime system to raise zerodivisionerror exceptionand the print statements will never be reached it would have been better to have written something along the lines of trysuccessfailureratio numsuccesses/float(numfailuresprint 'the success/failure ratio is'successfailureratio except zerodivisionerrorprint 'no failures so the success/failure ratio is undefined print 'now hereupon entering the try blockthe interpreter attempts to evaluate the expression numsuccesses/float(numfailuresif expression evaluation is successfulthe program assigns the value of the expression to the variable successfailureratioexecutes the print statement at the end of the try blockand proceeds to the print statement following the try-except ifhowevera zerodivisionerror exception is raised during the expression evaluationcontrol immediately jumps to the except block (skipping the assignment and the print statement in the try block)the print statement in the except block is executedand then execution continues at the print statement following the try-except block finger exerciseimplement function that meets the specification below use try-except block def sumdigits( )"""assumes is string returns the sum of the decimal digits in for exampleif is ' cit returns ""let' look at another example consider the code val int(raw_input('enter an integer')print 'the square of the number you entered is'val** if the user obligingly types string that can be converted to an integereverything will be fine but suppose the user types abcexecuting the line of code will cause the python runtime system to raise valueerror exceptionand the print statement will never be reached |
4,065 | exceptions and assertions what the programmer should have written would look something like while trueval raw_input('enter an integer'tryval int(valprint 'the square of the number you entered is'val** break #to exit the while loop except valueerrorprint val'is not an integerafter entering the loopthe program will ask the user to enter an integer once the user has entered somethingthe program executes the try--except block if neither of the first two statements in the try block causes valueerror exception to be raisedthe break statement is executed and the while loop is exited howeverif executing the code in the try block raises valueerror exceptioncontrol is immediately transferred to the code in the except block thereforeif the user enters string that does not represent an integerthe program will ask the user to try again no matter what text the user entersit will not cause an unhandled exception the downside of this change is that the program text has grown from two lines to eight if there are many places where the user is asked to enter an integerthis can be problematical of coursethis problem can be solved by introducing functiondef readint()while trueval raw_input('enter an integer'tryval int(valreturn val except valueerrorprint val'is not an integerbetter yetthis function can be generalized to ask for any type of inputdef readval(valtyperequestmsgerrormsg)while trueval raw_input(requestmsg 'tryval valtype(valreturn val except valueerrorprint valerrormsg the function readval is polymorphici it works for arguments of many different types such functions are easy to write in pythonsince types are firstclass values we can now ask for an integer using the code val readval(int'enter an integer:''is not an integer'exceptions may seem unfriendly (after allif not handledan exception will cause the program to crash)but consider the alternative what should the type conversion int dofor examplewhen asked to convert the string 'abcto an object of type intit could return an integer corresponding to the bits used to encode the stringbut this is unlikely to have any relation to the intent of the programmer alternativelyit could return the special value none if it did that |
4,066 | the programmer would need to insert code to check whether the type conversion had returned none programmer who forgot that check would run the risk of getting some strange error during program execution with exceptionsthe programmer still needs to include code dealing with the exception howeverif the programmer forgets to include such code and the exception is raisedthe program will halt immediately this is good thing it alerts the user of the program to the fact that something troublesome has happened (andas we discussed in the last overt bugs are much better than covert bugs moreoverit gives someone debugging the program clear indication of where things went awry if it is possible for block of program code to raise more than one kind of exceptionthe reserved word except can be followed by tuple of exceptionse except (valueerrortypeerror)in which case the except block will be entered if any of the listed exceptions is raised within the try block alternativelywe can write separate except block for each kind of exceptionwhich allows the program to choose an action based upon which exception was raised if the programmer writes exceptthe except block will be entered if any kind of exception is raised within the try block these features are shown in figure exceptions as control flow mechanism don' think of exceptions as purely for errors they are convenient flow-ofcontrol mechanism that can be used to simplify programs in many programming languagesthe standard approach to dealing with errors is to have functions return value (often something analogous to python' noneindicating that something has gone amiss each function invocation has to check whether that value has been returned in pythonit is more usual to have function raise an exception when it cannot produce result that is consistent with the function' specification the python raise statement forces specified exception to occur the form of raise statement is raise exceptionname(argumentsthe exceptionname is usually one of the built-in exceptionse valueerror howeverprogrammers can define new exceptions by creating subclass (see of the built-in class exception different types of exceptions can have different types of argumentsbut most of the time the argument is single stringwhich is used to describe the reason the exception is being raised |
4,067 | exceptions and assertions finger exerciseimplement function that satisfies the specification def findaneven( )"""assumes is list of integers returns the first even number in raises valueerror if does not contain an even number""consider the function definition in figure def getratios(vect vect )"""assumesvect and vect are lists of equal length of numbers returnsa list containing the meaningful values of vect [ ]/vect [ ]""ratios [for index in range(len(vect ))tryratios append(vect [index]/float(vect [index])except zerodivisionerrorratios append(float('nan')#nan not number exceptraise valueerror('getratios called with bad arguments'return ratios figure using exceptions for control flow there are two except blocks associated with the try block if an exception is raised within the try blockpython first checks to see if it is zerodivisionerror if soit appends special valuenanof type float to ratios (the value nan stands for "not number there is no literal for itbut it can be denoted by converting the string 'nanor the string 'nanto type float when nan is used as an operand in an expression of type floatthe value of that expression is also nan if the exception is anything other than zerodivisionerrorthe code executes the second except blockwhich raises valueerror exception with an associated string in principlethe second except block should never be enteredbecause the code invoking getratios should respect the assumptions in the specification of getratios howeversince checking these assumptions imposes only an insignificant computational burdenit is probably worth practicing defensive programming and checking anyway the following code illustrates how program might use getratios the name msg in the line except valueerrormsgis bound to the argument ( string in this caseassociated with valueerror when it was raised when executed |
4,068 | tryprint getratios([ , , , ][ , , , ]print getratios([][]print getratios([ ][ ]except valueerrormsgprint msg prints [ nan [getratios called with bad arguments figure contains an implementation of the same specificationbut without using try-except def getratios(vect vect )"""assumesvect and vect are lists of equal length of numbers returnsa list containing the meaningful values of vect [ ]/vect [ ]""ratios [if len(vect !len(vect )raise valueerror('getratios called with bad arguments'for index in range(len(vect ))vect elem vect [indexvect elem vect [indexif (type(vect elemnot in (intfloat))or (type(vect elemnot in (intfloat))raise valueerror('getratios called with bad arguments'if vect elem = ratios append(float('nan')#nan not number elseratios append(vect elem/vect elemreturn ratios figure control flow without try-except the code in figure is longer and more difficult to read than the code in figure it is also less efficient (the code in figure could be slightly shortened by eliminating the local variables vect elem and vect elembut only at the cost of introducing yet more inefficiency by accessing each element repeatedly let us look at one more example |
4,069 | exceptions and assertions def getgrades(fname)trygradesfile open(fname' '#open file for reading except ioerrorraise valueerror('getgrades could not open fnamegrades [for line in gradesfiletrygrades append(float(line)exceptraise valueerror('unable to convert line to float'return grades trygrades getgrades('quiz grades txt'grades sort(median grades[len(grades)// print 'median grade is'median except valueerrorerrormsgprint 'whoops 'errormsg figure get grades the function getgrades either returns value or raises an exception with which it has associated value it raises valueerror exception if the call to open raises an ioerror it could have ignored the ioerror and let the part of the program calling getgrades deal with itbut that would have provided less information to the calling code about what went wrong the code that uses getgrades either uses the returned value to compute another value or handles the exception and prints useful error message assertions the python assert statement provides programmers with simple way to confirm that the state of the computation is as expected an assert statement can take one of two formsassert boolean expression or assert boolean expressionargument when an assert statement is encounteredthe boolean expression is evaluated if it evaluates to trueexecution proceeds on its merry way if it evaluates to falsean assertionerror exception is raised assertions are useful defensive programming tool they can be used to confirm that the arguments to function are of appropriate types they are also useful debugging tool the can be usedfor exampleto confirm that intermediate values have the expected values or that function returns an acceptable value |
4,070 | we now turn our attention to our last major topic related to writing programs in pythonusing classes to organize programs around modules and data abstractions classes can be used in many different ways in this book we emphasize using them in the context of object-oriented programming the key to objectoriented programming is thinking about objects as collections of both data and the methods that operate on that data the ideas underlying object-oriented programming are about forty years oldand have been widely accepted and practiced over the last twenty years or so in the mid- people began to write articles explaining the benefits of this approach to programming about the same timethe programming languages smalltalk (at xerox parcand clu (at mitprovided linguistic support for the ideas but it wasn' until the arrival of +and java that it really took off in practice we have been implicitly relying on object-oriented programming throughout most of this book back in section we said "objects are the core things that python programs manipulate every object has type that defines the kinds of things that programs can do with objects of that type since we have relied heavily upon built-in types such as list and dict and the methods associated with those types but just as the designers of programming language can build in only small fraction of the useful functionsthey can only build in only small fraction of the useful types we have already looked at mechanism that allows programmers to define new functionswe now look at mechanism that allows programmers to define new types abstract data types and classes the notion of an abstract data type is quite simple an abstract data type is set of objects and the operations on those objects these are bound together so that one can pass an object from one part of program to anotherand in doing so provide access not only to the data attributes of the object but also to operations that make it easy to manipulate that data the specifications of those operations define an interface between the abstract data type and the rest of the program the interface defines the behavior of the operations--what they dobut not how they do it the interface thus provides an abstraction barrier that isolates the rest of the program from the data structuresalgorithmsand code involved in providing realization of the type abstraction programming is about managing complexity in way that facilitates change there are two powerful mechanisms available for accomplishing thisdecomposition and abstraction decomposition creates structure in programand abstraction suppresses detail the key is to suppress the appropriate |
4,071 | classes and object-oriented programming details this is where data abstraction hits the mark one can create domainspecific types that provide convenient abstraction ideallythese types capture concepts that will be relevant over the lifetime of program if one starts the programming process by devising types that will be relevant months and even decades laterone has great leg up in maintaining that software we have been using abstract data types (without calling them thatthroughout this book we have written programs using integerslistsfloating point numbersstringsand dictionaries without giving any thought to how these types might be implemented to paraphrase moliere' bourgeois gentilhomme"par ma foiil plus de quatre-vingt pages que nous avons utilise adtssans que nous le sachions " in pythonone implements data abstractions using classes figure contains class definition that provides straightforward implementation of set-ofintegers abstraction called intset class definition creates an object of type type and associates with that object set of objects of type instancemethod for examplethe expression intset insert refers to the method insert defined in the definition of the class intset and the code print type(intset)type(intset insertwill print notice that the docstring (the comment enclosed in """at the top of the class definition describes the abstraction provided by the classnot information about how the class is implemented the comment below the docstring does contain information about the implementation that information is aimed at programmers who might want to modify the implementation or build subclasses (see section of the classnot at programmers who might want to use the abstraction "good heavensfor more than eighty pages we have been using adts without knowing it |
4,072 | class intset(object)"""an intset is set of integers""#information about the implementation (not the abstraction#the value of the set is represented by list of intsself vals #each int in the set occurs in self vals exactly once def __init__(self)"""create an empty set of integers""self vals [def insert(selfe)"""assumes is an integer and inserts into self""if not in self valsself vals append(edef member(selfe)"""assumes is an integer returns true if is in selfand false otherwise""return in self vals def remove(selfe)"""assumes is an integer and removes from self raises valueerror if is not in self""tryself vals remove(eexceptraise valueerror(str(enot found'def getmembers(self)"""returns list containing the elements of self nothing can be assumed about the order of the elements""return self vals[:def __str__(self)"""returns string representation of self""self vals sort(result 'for in self valsresult result str( ',return '{result[:- '}#- omits trailing comma figure class intset when function definition occurs within class definitionthe defined function is called method and is associated with the class these methods are sometimes referred to as method attributes of the class if this seems confusing at the momentdon' worry about it we will have lots more to say about this topic later in this classes support two kinds of operationsinstantiation is used to create instances of the class for examplethe statement intset(creates new object of type intset this object is called an instance of intset attribute references use dot notation to access attributes associated with the class for examples member refers to the method member associated with the instance of type intset |
4,073 | classes and object-oriented programming each class definition begins with the reserved word class followed by the name of the class and some information about how it relates to other classes in this casethe first line indicates that intset is subclass of object for nowignore what it means to be subclass we will get to that shortly as we will seepython has number of special method names that start and end with two underscores the first of these we will look at is __init__ whenever class is instantiateda call is made to the __init__ method defined in that class when the line of code intset(is executedthe interpreter will create new instance of type intsetand then call intset __init__ with the newly created object as the actual parameter that is bound to the formal parameter self when invokedintset __init__ creates valsan object of type listwhich becomes part of the newly created instance of type intset (the list is created using the by now familiar notation []which is simply an abbreviation for list(this list is called data attribute of the instance of intset notice that each object of type intset will have different vals listas one would expect as we have seenmethods associated with an instance of class can be invoked using dot notation for examplethe codes intset( insert( print member( creates new instance of intsetinserts the integer into that intsetand then prints true at first blush there appears to be something inconsistent here it looks as if each method is being called with one argument too few for examplemember has two formal parametersbut we appear to be calling it with only one actual parameter this is an artifact of the dot notation the object associated with the expression preceding the dot is implicitly passed as the first parameter to the method throughout this bookwe follow the convention of using self as the name of the formal parameter to which this actual parameter is bound python programmers observe this convention almost universallyand we strongly suggest that you use it as well class should not be confused with instances of that classjust as an object of type list should not be confused with the list type attributes can be associated either with class itself or with instances of classmethod attributes are defined in class definitionfor example intset member is an attribute of the class intset when the class is instantiatede by intset()instance attributese memberare created keep in mind that intset member and member are different objects while member is initially bound to the member method defined in the class intsetthat binding can be changed during the course of computation for exampleyou could (but shouldn' !write member intset insert |
4,074 | when data attributes are associated with class we call them class variables when they are associated with an instance we call them instance variables for examplevals is an instance variable because for each instance of class intsetvals is bound to different list so farwe haven' seen class variable we will use one in figure data abstraction achieves representation-independence think of the implementation of an abstract type as having several componentsimplementations of the methods of the typedata structures that together encode values of the typeand conventions about how the implementations of the methods are to use the data structures key convention is captured by the representation invariant the representation invariant defines which values of the data attributes correspond to valid representations of class instances the representation invariant for intset is that vals contains no duplicates the implementation of __init__ is responsible for establishing the invariant (which holds on the empty list)and the other methods are responsible for maintaining that invariant that is why insert appends only if it is not already in self vals the implementation of remove exploits the assumption that the representation invariant is satisfied when remove is entered it calls list remove only oncesince the representation invariant guarantees that there is at most one occurrence of in self vals the last method defined in the class__str__is another one of those special __ methods when the print command is usedthe __str__ function associated with the object to be printed is automatically invoked for examplethe code intset( insert( insert( print will print{ , (if no __str__ method were definedprint would cause something like to be printed we could also print the value of by writing print __str__(or even print intset __str__( )but using those forms is less convenient the __str__ method of class is also invoked when program converts an instance of that class to string by calling str |
4,075 | classes and object-oriented programming designing programs using abstract data types abstract data types are big deal they lead to different way of thinking about organizing large programs when we think about the worldwe rely on abstractions in the world of finance people talk about stocks and bonds in the world of biology people talk about proteins and residues when trying to understand these conceptswe mentally gather together some of the relevant data and features of these kinds of objects into one intellectual package for examplewe think of bonds as having an interest rate and maturity date as data attributes we also think of bonds as having operations such as "set priceand "calculate yield to maturity abstract data types allow us to incorporate this kind of organization into the design of programs data abstraction encourages program designers to focus on the centrality of data objects rather than functions thinking about program more as collection of types than as collection of functions leads to profoundly different organizing principle among other thingsit encourages one to think about programming as process of combining relatively large chunkssince data abstractions typically encompass more functionality than do individual functions thisin turnleads us to think of the essence of programming as process not of writing individual lines of codebut of composing abstractions the availability of reusable abstractions not only reduces development timebut also usually leads to more reliable programsbecause mature software is usually more reliable than new software for many yearsthe only program libraries in common use were statistical or scientific todayhoweverthere is great range of available program libraries (especially for python)often based on rich set of data abstractionsas we shall see later in this book using classes to keep track of students and faculty as an example use of classesimagine that you are designing program to help keep track of all the students and faculty at university it is certainly possible to write such program without using data abstraction each student would have family namea given namea home addressa yearsome gradesetc this could all be kept in some combination of lists and dictionaries keeping track of faculty and staff would require some similar data structures and some different data structurese data structures to keep track of things like salary history before rushing in to design bunch of data structureslet' think about some abstractions that might prove useful is there an abstraction that covers the common attributes of studentsprofessorsand staffsome would argue that they are all human figure contains class that incorporates some of the common attributes (name and birthdateof humans it makes use of the standard python library module datetimewhich provides many convenient methods for creating and manipulating dates |
4,076 | import datetime class person(object)def __init__(selfname)"""create person""self name name trylastblank name rindex('self lastname name[lastblank+ :exceptself lastname name self birthday none def getname(self)"""returns self' full name""return self name def getlastname(self)"""returns self' last name""return self lastname def setbirthday(selfbirthdate)"""assumes birthdate is of type datetime date sets self' birthday to birthdate""self birthday birthdate def getage(self)"""returns self' current age in days""if self birthday =noneraise valueerror return (datetime date today(self birthdaydays def __lt__(selfother)"""returns true if self' name is lexicographically less than other' nameand false otherwise""if self lastname =other lastnamereturn self name other name return self lastname other lastname def __str__(self)"""returns self' name""return self name figure class person the following code makes use of person me person('michael guttag'him person('barack hussein obama'her person('madonna'print him getlastname(him setbirthday(datetime date( )her setbirthday(datetime date( )print him getname()'is'him getage()'days oldnotice that whenever person is instantiated an argument is supplied to the __init__ function in generalwhen instantiating class we need to look at the |
4,077 | classes and object-oriented programming specification of the __init__ function for that class to know what arguments to supply and what properties those arguments should have after this code is executedthere will be three instances of class person one can then access information about these instances using the methods associated with them for examplehim getlastname(will return 'obamathe expression him lastname will also return 'obama'howeverfor reasons discussed later in this writing expressions that directly access instance variables is considered poor formand should be avoided similarlythere is no appropriate way for user of the person abstraction to extract person' birthdaydespite the fact that the implementation contains an attribute with that value there ishowevera way to extract information that depends upon the person' birthdayas illustrated by the last print statement in the above code class person defines yet another specially named method__lt__ this method overloads the operator the method person__lt__ gets called whenever the first argument to the operator is of type person the __lt__ method in class person is implemented using the operator of type str the expression self name other name is shorthand for self name __lt__(self othersince self name is of type strthe __lt__ method is the one associated with type str in addition to providing the syntactic convenience of writing infix expressions that use <this overloading provides automatic access to any polymorphic method defined using __lt__ the built-in method sort is one such method sofor exampleif plist is list composed of elements of type personthe call plist sort(will sort that list using the __lt__ method defined in class person the code plist [mehimherfor in plistprint plist sort(for in plistprint will first print michael guttag barack hussein obama madonna and then print michael guttag madonna barack hussein obama |
4,078 | inheritance many types have properties in common with other types for exampletypes list and str each have len functions that mean the same thing inheritance provides convenient mechanism for building groups of related abstractions it allows programmers to create type hierarchy in which each type inherits attributes from the types above it in the hierarchy the class object is at the top of the hierarchy this makes sensesince in python everything that exists at runtime is an object because person inherits all of the properties of objectsprograms can bind variable to personappend person to listetc the class mitperson in figure inherits attributes from its parent classpersonincluding all of the attributes that person inherited from its parent classobject class mitperson(person)nextidnum #identification number def __init__(selfname)person __init__(selfnameself idnum mitperson nextidnum mitperson nextidnum + def getidnum(self)return self idnum def __lt__(selfother)return self idnum other idnum figure class mitperson in the jargon of object-oriented programmingmitperson is subclass of personand therefore inherits the attributes of its superclass in addition to what it inheritsthe subclass canadd new attributes for examplemitperson has added the class variable nextidnumthe instance variable idnumand the method getidnum override attributes of the superclass for examplemitperson has overridden __init__ and __lt__ the method mitperson __init__ first invokes person __init__ to initialize the inherited instance variable self name it then initializes self idnuman instance variable that instances of mitperson have but instances of person do not the instance variable self idnum is initialized using class variablenextidnumthat belongs to the class mitpersonrather than to instances of the class when an instance of mitperson is createda new instance of nextidnum is not created this allows __init__ to ensure that each instance of mitperson has unique idnum |
4,079 | classes and object-oriented programming consider the code mitperson('barbara beaver'print str( '\' id number is str( getidnum()the first line creates new mitperson the second line is bit more complicated when it attempts to evaluate the expression str( )the runtime system first checks to see if there is an __str__ method associated with class mitperson since there is notit next checks to see if there is an __str__ method associated with the superclasspersonof mitperson there isso it uses that when the runtime system attempts to evaluate the expression getidnum()it first checks to see if there is getidnum method associated with class mitperson there isso it invokes that method and prints barbara beaver' id number is (recall that in stringthe character "\is an escape character used to indicate that the next character should be treated in special way in the string '\' id number is the "\indicates that the apostrophe is part of the stringnot delimiter terminating the string now consider the code mitperson('mark guttag' mitperson('billy bob beaver' mitperson('billy bob beaver' person('billy bob beaver'we have created four virtual peoplethree of whom are named billy bob beaver two of the billy bobs are of type mitpersonand one merely person if we execute the lines of code print ' =' print ' =' print ' =' the interpreter will print true false true since and are all of type mitpersonthe interpreter will use the __lt__ method defined in class mitperson when evaluating the first two comparisonsso the ordering will be based on identification numbers in the third comparisonthe operator is applied to operands of different types since the first argument of the expression is used to determine which __lt__ method to invokep is shorthand for __lt__( thereforethe interpreter uses the __lt__ method associated with the type of personand the "peoplewill be ordered by name what happens if we try print ' =' |
4,080 | the interpreter will invoke the __lt__ operator associated with the type of the one defined in class mitperson this will lead to the exception attributeerror'personobject has no attribute 'idnumbecause the object to which is bound does not have an attribute idnum multiple levels of inheritance figure adds another couple of levels of inheritance to the class hierarchy class student(mitperson)pass class ug(student)def __init__(selfnameclassyear)mitperson __init__(selfnameself year classyear def getclass(self)return self year class grad(student)pass figure two kinds of students adding ug seems logicalbecause we want to associate year of graduation (or perhaps anticipated graduationwith each undergraduate but what is going on with the classes student and gradby using the python reserved word pass as the bodywe indicate that the class has no attributes other than those inherited from its superclass why would one ever want to create class with no new attributesby introducing the class gradwe gain the ability to create two different kinds of students and use their types to distinguish one kind of object from another for examplethe code grad('buzz aldrin' ug('billy beaver' print 'is graduate student is'type( =grad print 'is an undergraduate student is'type( =ug will print buzz aldrin is graduate student is true buzz aldrin is an undergraduate student is false the utility of the intermediate type student is bit subtler consider going back to class mitperson and adding the method def isstudent(self)return isinstance(selfstudentthe function isinstance is built into python the first argument of isinstance can be any objectbut the second argument must be an object of type type the function returns true if and only if the first argument is an instance of the second argument for example the value of isinstance([ , ]listis true |
4,081 | classes and object-oriented programming returning to our examplethe code print 'is student is' isstudent(print 'is student is' isstudent(print 'is student is' isstudent(prints buzz aldrin is student is true billy beaver is student is true billy bob beaver is student is false notice that isinstance( studentis quite different from type( =student the object to which is bound is of type ugnot studentbut since ug is subclass of studentthe object to which is bound is considered to be an instance of class student (as well as an instance of mitperson and personsince there are only two kinds of studentswe could have implemented isstudent asdef isstudent(self)return type(self=grad or type(self=ug howeverif new type of student were introduced at some later point it would be necessary to go back and edit the code implementing isstudent by introducing the intermediate class student and using isinstance we avoid this problem for exampleif we were to add class transferstudent(student)def __init__(selfnamefromschool)mitperson __init__(selfnameself fromschool fromschool def getoldschool(self)return self fromschool no change needs to be made to isstudent it is not unusual during the creation and later maintenance of program to go back and add new classes or new attributes to old classes good programmers design their programs so as to minimize the amount of code that might need to be changed when that is done the substitution principle when subclassing is used to define type hierarchythe subclasses should be thought of as extending the behavior of their superclasses we do this by adding new attributes or overriding attributes inherited from superclass for exampletransferstudent extends student by introducing former school sometimesthe subclass overrides methods from the superclassbut this must be done with care in particularimportant behaviors of the supertype must be supported by each of its subtypes if client code works correctly using an instance of the supertypeit should also work correctly when an instance of the subtype is substituted for the instance of the supertype for exampleit should |
4,082 | be possible to write client code using the specification of student and have it work correctly on transferstudent converselythere is no reason to expect that code written to work for transferstudent should work for arbitrary types of student encapsulation and information hiding as long as we are dealing with studentsit would be shame not to make them suffer through taking classes and getting grades class grades(object)""" mapping from students to list of grades""def __init__(self)"""create empty grade book""self students [self grades {self issorted true def addstudent(selfstudent)"""assumesstudent is of type student add student to the grade book""if student in self studentsraise valueerror('duplicate student'self students append(studentself grades[student getidnum()[self issorted false def addgrade(selfstudentgrade)"""assumesgrade is float add grade to the list of grades for student""tryself grades[student getidnum()append(gradeexceptraise valueerror('student not in mapping'def getgrades(selfstudent)"""return list of grades for student""try#return copy of student' grades return self grades[student getidnum()][:exceptraise valueerror('student not in mapping'def getstudents(self)"""return list of the students in the grade book""if not self issortedself students sort(self issorted true return self students[:#return copy of list of students figure class grades this substitution principle was first clearly enunciated by barbara liskov and jeannette wing in their paper" behavioral notion of subtyping |
4,083 | classes and object-oriented programming figure contains class that can be used to keep track of the grades of collection of students instances of class grades are implemented using list and dictionary the list keeps track of the students in the class the dictionary maps student' identification number to list of grades notice that getgrades returns copy of the list of grades associated with studentand getstudents returns copy of the list of students the computational cost of copying the lists could have been avoided by simply returning the instance variables themselves doing sohoweveris likely to lead to problems consider the code allstudents course getstudents(allstudents extend(course getstudents()if getstudents returned self studentsthe second line of code would have the (probably unexpectedside effect of changing the set of students in course the instance variable issorted is used to keep track of whether or not the list of students has been sorted since the last time student was added to it this allows the implementation of getstudents to avoid sorting an already sorted list figure contains function that uses class grades to produce grade report for some students taking the mit course for which this book was developed |
4,084 | def gradereport(course)"""assumes course is of type grades""report 'for in course getstudents()tot numgrades for in course getgrades( )tot + numgrades + tryaverage tot/numgrades report report '\ 'str( '\' mean grade is str(averageexcept zerodivisionerrorreport report '\ 'str(shas no gradesreturn report ug ug('jane doe' ug ug('john doe' ug ug('david henry' grad('billy buckner' grad('bucky dent'sixhundred grades(sixhundred addstudent(ug sixhundred addstudent(ug sixhundred addstudent( sixhundred addstudent( for in sixhundred getstudents()sixhundred addgrade( sixhundred addgrade( sixhundred addgrade( sixhundred addstudent(ug print gradereport(sixhundredfigure generating grade report when runthe code in the figure prints jane doe' mean grade is john doe' mean grade is david henry has no grades billy buckner' mean grade is bucky dent' mean grade is there are two important concepts at the heart of object-oriented programming the first is the idea of encapsulation by this we mean the bundling together of data attributes and the methods for operating on them for exampleif we write rafael mitperson(we can use dot notation to access attributes such as rafael' age and identification number the second important concept is information hiding this is one of the keys to modularity if those parts of the program that use class ( the clients of the classrely only on the specifications of the methods in the classa programmer implementing the class is free to change the implementation of the class ( to |
4,085 | classes and object-oriented programming improve efficiencywithout worrying that the change will break code that uses the class some programming languages (java and ++for exampleprovide mechanisms for enforcing information hiding programmers can make the data attributes of class invisible to clients of the classand thus require that the data be accessed only through the object' methods sofor examplewe could get the idnum associated with rafael by executing rafael getidnum(but not by writing rafael idnum unfortunatelypython does not provide mechanisms for enforcing information hiding there is no way for the implementer of class to restrict access to the attributes of class instances for examplea client of person can write the expression rafael lastname rather than rafael getlastname(why is this unfortunatebecause the client code is relying upon something that is not part of the specification of personand is therefore subject to change if the implementation of person were changedfor example to extract the last name whenever it is requested rather than store it in an instance variablethen the client code would no longer work not only does python let programs read instance and class variables from outside the class definitionit also lets programs write these variables sofor examplethe code rafael birthday 'is perfectly legal this would lead to runtime type errorwere rafael getage invoked later in the computation it is even possible to create instance variables from outside the class definition for examplepython will not complain if the assignment statement me age rafael getage(occurs outside the class definition while this weak static semantic checking is flaw in pythonit is not fatal flaw disciplined programmer can simply follow the sensible rule of not directly accessing data attributes from outside the class in which they are definedas we do in this book generators perceived risk of information hiding is that preventing client programs from directly accessing critical data structures leads to an unacceptable loss of efficiency in the early days of data abstractionmany were concerned about the cost of introducing extraneous function/method calls modern compilation technology makes this concern moot more serious issue is that client programs will be forced to use inefficient algorithms consider the implementation of gradereport in figure the invocation of course getstudents creates and returns list of size nwhere is the number of students this is probably not problem for grade book for single classbut imagine keeping track of the grades of million high school students taking the sat' creating new list of that size when the list already exists is significant inefficiency one solution is to abandon the abstraction and allow gradereport to directly access the instance variable course studentsbut that would violate information hiding fortunatelythere is better solution |
4,086 | the code in figure replaces the getstudents function in class grades with function that uses kind of statement we have not yet useda yield statement def getstudents(self)"""return the students in the grade book one at time""if not self issortedself students sort(self issorted true for in self studentsyield figure new version of getstudents any function definition containing yield statement is treated in special way the presence of yield tells the python system that the function is generator generators are typically used in conjunction with for statements at the start of the first iteration of for loopthe interpreter starts executing the code in the body of the generator it runs until the first time yield statement is executedat which point it returns the value of the expression in the yield statement on the next iterationthe generator resumes execution immediately following the yieldwith all local variables bound to the objects to which they were bound when the yield statement was executedand again runs until yield statement is executed it continues to do this until it runs out of code to execute or executes return statementat which point the loop is exited the version of getstudents in figure allows programmers to use for loop to iterate over the students in objects of type grades in the same way they can use for loop to iterate over elements of built-in types such as list for examplethe code book grades(book addstudent(grad('julie')book addstudent(grad('charlie')for in book getstudents()print prints julie charlie thus the loop in figure that starts with for in course getstudents()does not have to be altered to take advantage of the version of class grades that contains the new implementation of getstudents the same for loop can iterate over the values provided by getstudents regardless of whether getstudents returns list of values or generates one value at time generating one value at this explanation of generators is bit simplistic to fully understand generatorsyou need to understand the way built-in iterators are implemented in pythonwhich is not covered in this book |
4,087 | classes and object-oriented programming time will be more efficientbecause new list containing the students will not be created mortgagesan extended example collapse in housing prices helped trigger severe economic meltdown in the fall of one of the contributing factors was that many homeowners had taken on mortgages that ended up having unexpected consequences in the beginningmortgages were relatively simple beasts one borrowed money from bank and made fixed-size payment each month for the life of the mortgagewhich typically ranged from fifteen to thirty years at the end of that periodthe bank had been paid back the initial loan (the principalplus interestand the homeowner owned the house "free and clear towards the end of the twentieth centurymortgages started getting lot more complicated people could get lower interest rates by paying "pointsat the time they took on the mortgage point is cash payment of of the value of the loan people could take mortgages that were "interest-onlyfor period of time that is to sayfor some number of months at the start of the loan the borrower paid only the accrued interest and none of the principal other loans involved multiple rates typically the initial rate (called "teaser rate"was lowand then it went up over time many of these loans were variable-rate--the rate to be paid after the initial period would vary depending upon some index intended to reflect the cost to the lender of borrowing on the wholesale credit market in principlegiving consumers variety of options is good thing howeverunscrupulous loan purveyors were not always careful to fully explain the possible long-term implications of the various optionsand some borrowers made choices that proved to have dire consequences let' build program that examines the costs of three kinds of loansa fixed-rate mortgage with no pointsa fixed-rate mortgage with pointsand mortgage with an initial teaser rate followed by higher rate for the duration the point of this exercise is to provide some experience in the incremental development of set of related classesnot to make you an expert on mortgages we will structure our code to include mortgage classand subclasses corresponding to each of the three kinds of mortgages listed above in this contextit is worth recalling the etymology of the word mortgage the american heritage dictionary of the english language traces the word back to the old french words for dead (mortand pledge (gage(this derivation also explains why the "tin the middle of mortgage is silent the london interbank offered rate (liboris probably the most commonly used index |
4,088 | figure contains the abstract class mortgage this class contains methods that are shared by each of the subclassesbut it is not intended to be instantiated directly the function findpayment at the top of the figure computes the size of the fixed monthly payment needed to pay off the loanincluding interestby the end of its term it does this using well-known closed-form expression this expression is not hard to derivebut it is lot easier to just look it up and more likely to be correct than one derived on the spot when your code incorporates formulas you have looked upmake sure thatyou have taken the formula from reputable source we looked at multiple reputable sourcesall of which contained equivalent formulas you fully understand the meaning of all the variables in the formula you test your implementation against examples taken from reputable sources after implementing this functionwe tested it by comparing our results to the results supplied by calculator available on the web def findpayment(loanrm)"""assumesloan and are floatsm an int returns the monthly payment for mortgage of size loan at monthly rate of for months""return loan*(( *( + )** )/(( + )** )class mortgage(object)"""abstract class for building different kinds of mortgages""def __init__(selfloanannratemonths)"""create new mortgage""self loan loan self rate annrate/ self months months self paid [ self owed [loanself payment findpayment(loanself ratemonthsself legend none #description of mortgage def makepayment(self)"""make payment""self paid append(self paymentreduction self payment self owed[- ]*self rate self owed append(self owed[- reductiondef gettotalpaid(self)"""return the total amount paid so far""return sum(self paiddef __str__(self)return self legend figure mortgage base class looking at __init__we see that all mortgage instances will have instance variables corresponding to the initial loan amountthe monthly interest ratethe duration of the loan in monthsa list of payments that have been made at the start of each month (the list starts with since no payments have been made at the start of the first month) list with the balance of the loan that is |
4,089 | classes and object-oriented programming outstanding at the start of each monththe amount of money to be paid each month (initialized using the value returned by the function findpayment)and description of the mortgage (which initially has value of nonethe __init__ operation of each subclass of mortgage is expected to start by calling mortgage __init__and then to initialize self legend to an appropriate description of that subclass the method makepayment is used to record mortgage payments part of each payment covers the amount of interest due on the outstanding loan balanceand the remainder of the payment is used to reduce the loan balance that is why makepayment updates both self paid and self owed the method gettotalpaid uses the built-in python function sumwhich returns the sum of sequence of numbers if the sequence contains non-numberan exception is raised figure contains classes implementing two types of mortgage each of these classes overrides __init__ and inherits the other three methods from mortgage class fixed(mortgage)def __init__(selfloanrmonths)mortgage __init__(selfloanrmonthsself legend 'fixedstr( * '%class fixedwithpts(mortgage)def __init__(selfloanrmonthspts)mortgage __init__(selfloanrmonthsself pts pts self paid [loan*(pts/ )self legend 'fixedstr( * '%'str(ptspointsfigure fixed-rate mortgage classes figure contains third subclass of mortgage the class tworate treats the mortgage as the concatenation of two loanseach at different interest rate (since self paid is initialized with it contains one more element than the number of payments that have been made that' why makepayment compares len(self paidto self teasermonths |
4,090 | class tworate(mortgage)def __init__(selfloanrmonthsteaserrateteasermonths)mortgage __init__(selfloanteaserratemonthsself teasermonths teasermonths self teaserrate teaserrate self nextrate / self legend str(teaserrate* )'for str(self teasermonths)monthsthen str( * '%def makepayment(self)if len(self paid=self teasermonths self rate self nextrate self payment findpayment(self owed[- ]self rateself months self teasermonthsmortgage makepayment(selffigure mortgage with teaser rate figure contains function that computes and prints the total cost of each kind of mortgage for sample set of parameters it begins by creating one mortgage of each kind it then makes monthly payment on each for given number of years finallyit prints the total amount of the payments made for each loan def comparemortgages(amtyearsfixedrateptsptsratevarrate varrate varmonths)totmonths years* fixed fixed(amtfixedratetotmonthsfixed fixedwithpts(amtptsratetotmonthsptstworate tworate(amtvarrate totmonthsvarrate varmonthsmorts [fixed fixed tworatefor in range(totmonths)for mort in mortsmort makepayment(for in mortsprint print total payments $str(int( gettotalpaid())comparemortgages(amt= years= fixedrate= pts ptsrate= varrate = varrate = varmonths= figure evaluate mortgages notice that we used keyword rather than positional arguments in the invocation of comparemortgages we did this because comparemortgages has large number of formal parameters and using keyword arguments makes it easier to ensure that we are supplying the intended actual values to each of the formals |
4,091 | classes and object-oriented programming when the code in figure is runit prints fixed total payments $ fixed % points total payments $ for monthsthen total payments $ at first glancethe results look pretty conclusive the variable-rate loan is bad idea (for the borrowernot the bankand the fixed-rate loan with points costs the least it' important to notehoweverthat total cost is not the only metric by which mortgages should be judged for examplea borrower who expects to have higher income in the future may be willing to pay more in the later years to lessen the burden of payments in the beginning this suggests that rather than looking at single numberwe should look at payments over time this in turn suggests that our program should be producing plots designed to show how the mortgage behaves over time we will do that in section |
4,092 | complexity the most important thing to think about when designing and implementing program is that it should produce results that can be relied upon we want our bank balances to be calculated correctly we want the fuel injectors in our automobiles to inject appropriate amounts of fuel we would prefer that neither airplanes nor operating systems crash sometimes performance is an important aspect of correctness this is most obvious for programs that need to run in real time program that warns airplanes of potential obstructions needs to issue the warning before the obstructions are encountered performance can also affect the utility of many non-real-time programs the number of transactions completed per minute is an important metric when evaluating the utility of database systems users care about the time required to start an application on their phone biologists care about how long their phylogenetic inference calculations take writing efficient programs is not easy the most straightforward solution is often not the most efficient computationally efficient algorithms often employ subtle tricks that can make them difficult to understand consequentlyprogrammers often increase the conceptual complexity of program in an effort to reduce its computational complexity to do this in sensible waywe need to understand how to go about estimating the computational complexity of program that is the topic of this thinking about computational complexity how should one go about answering the question "how long will the following function take to run?def ( )"""assumes is an int and > ""answer while > answer * - return answer we could run the program on some input and time it but that wouldn' be particularly informative because the result would depend upon the speed of the computer on which it is run the efficiency of the python implementation on that machineand the value of the input we get around the first two issues by using more abstract measure of time instead of measuring time in millisecondswe measure time in terms of the number of basic steps executed by the program |
4,093 | simplistic introduction to algorithmic complexity for simplicitywe will use random access machine as our model of computation in random access machinesteps are executed sequentiallyone at time step is an operation that takes fixed amount of timesuch as binding variable to an objectmaking comparisonexecuting an arithmetic operationor accessing an object in memory now that we have more abstract way to think about the meaning of timewe turn to the question of dependence on the value of the input we deal with that by moving away from expressing time complexity as single number and instead relating it to the sizes of the inputs this allows us to compare the efficiency of two algorithms by talking about how the running time of each grows with respect to the sizes of the inputs of coursethe actual running time of an algorithm depends not only upon the sizes of the inputs but also upon their values considerfor examplethe linear search algorithm implemented by def linearsearch(lx)for in lif =xreturn true return false suppose that is million elements long and consider the call linearsearch( if the first element in is linearsearch will return true almost immediately on the other handif is not in llinearsearch will have to examine all one million elements before returning false in generalthere are three broad cases to think aboutthe best-case running time is the running time of the algorithm when the inputs are as favorable as possible the best-case running time is the minimum running time over all the possible inputs of given size for linearsearchthe best-case running time is independent of the size of similarlythe worst-case running time is the maximum running time over all the possible inputs of given size for linearsearchthe worstcase running time is linear in the size of the list by analogy with the definitions of the best-case and worst-case running timethe average-case (also called expected-caserunning time is the average running time over all possible inputs of given size alternativelyif one has some priori information about the distribution of input values ( that of the time is in )one can take that into account people usually focus on the worst case all engineers share common article of faithmurphy' lawif something can go wrongit will go wrong the worst-case provides an upper bound on the running time this is critical in situations where there is time constraint on how long computation can take it is not more accurate model for today' computers might be parallel random access machine howeverthat adds considerable complexity to the algorithmic analysisand often doesn' make an important qualitative difference in the answer |
4,094 | good enough to know that "most of the timethe air traffic control system warns of impending collisions before they occur let' look at the worst-case running time of an iterative implementation of the factorial function def fact( )"""assumes is natural number returns !""answer while answer * - return answer the number of steps required to run this program is something like ( for the initial assignment statement and one for the return (counting step for the test in the while steps for the first assignment statement in the while loop and steps for the second assignment statement in the loopsofor exampleif is the function will execute roughly steps it should be immediately obvious that as gets largeworrying about the difference between and + is kind of silly for this reasonwe typically ignore additive constants when reasoning about running time multiplicative constants are more problematical should we care whether the computation takes steps or stepsmultiplicative factors can be important whether search engine takes half second or seconds to service query can be the difference between whether people use that search engine or go to competitor on the other handwhen one is comparing two different algorithmsit is often the case that even multiplicative constants are irrelevant recall that in we looked at two algorithmsexhaustive enumeration and bisection searchfor finding an approximation to the square root of floating point number functions based on each of these algorithms are shown in figure and figure def squarerootexhaustive(xepsilon)"""assumes and epsilon are positive floats epsilon returns such that * is within epsilon of ""step epsilon** ans while abs(ans** >epsilon and ans*ans <xans +step if ans*ans xraise valueerror return ans figure using exhaustive enumeration to approximate square root |
4,095 | simplistic introduction to algorithmic complexity def squarerootbi(xepsilon)"""assumes and epsilon are positive floats epsilon returns such that * is within epsilon of ""low high max( xans (high low)/ while abs(ans** >epsilonif ans** xlow ans elsehigh ans ans (high low)/ return ans figure using bisection search to approximate square root we saw that exhaustive enumeration was so slow as to be impractical for many combinations of and epsilon for exampleevaluating squarerootexhaustive( requires roughly one billion iterations of the loop in contrastevaluating squarerootbi( takes roughly twenty iterations of slightly more complex while loop when the difference in the number of iterations is this largeit doesn' really matter how many instructions are in the loop the multiplicative constants are irrelevant asymptotic notation we use something called asymptotic notation to provide formal way to talk about the relationship between the running time of an algorithm and the size of its inputs the underlying motivation is that almost any algorithm is sufficiently efficient when run on small inputs what we typically need to worry about is the efficiency of the algorithm when run on very large inputs as proxy for "very large,asymptotic notation describes the complexity of an algorithm as the size of its inputs approaches infinity considerfor examplethe code def ( )"""assume is an int ""ans #loop that takes constant time for in range( )ans + print 'number of additions so far'ans #loop that takes time for in range( )ans + print 'number of additions so far'ans #nested loops take time ** for in range( )for in range( )ans + ans + print 'number of additions so far'ans return ans |
4,096 | if one assumes that each line of code takes one unit of time to executethe running time of this function can be described as the constant corresponds to the number of times the first loop is executed the term corresponds to the number of times the second loop is executed finallythe term corresponds to the time spent executing the two statements in the nested for loop consequentlythe call ( will print number of additions so far number of additions so far number of additions so far for small values of the constant term dominates if is of the steps are accounted for by the first loop on the other handif is each of the first two loops accounts for only of the steps when is , , the first loop takes about of the total time and the second loop about full , , , , of the , , , , steps are in the body of the inner for loop clearlywe can get meaningful notion of how long this code will take to run on very large inputs by considering only the inner loopi the quadratic component should we care about the fact that this loop takes steps rather than stepsif your computer executes roughly million steps per secondevaluating will take about hours if we could reduce the complexity to stepsit would take about hours in either casethe moral is the samewe should probably look for more efficient algorithm this kind of analysis leads us to use the following rules of thumb in describing the asymptotic complexity of an algorithmif the running time is the sum of multiple termskeep the one with the largest growth rateand drop the others if the remaining term is productdrop any constants the most commonly used asymptotic notation is called "big onotation big notation is used to give an upper bound on the asymptotic growth (often called the order of growthof function for examplethe formula (xo( means that the function grows no faster than the quadratic polynomial in an asymptotic sense welike many computer scientistswill often abuse big notation by making statements like"the complexity of (xis ( by this we mean that in the worst case will take ( steps to run the difference between function being "in ( )and "being ( )is subtle but important saying that (xo ( does not preclude the worst-case running time of from being considerably less that ( the phrase "big owas introduced in this context by the computer scientist donald knuth in the he chose the greek letter omicron because number theorists had used that letter since the late th century to denote related concept |
4,097 | simplistic introduction to algorithmic complexity when we say that (xis ( )we are implying that is both an upper and lower bound on the asymptotic worst-case running time this is called tight bound some important complexity classes some of the most common instances of big are listed below in each casen is measure of the size of the inputs to the function ( denotes constant running time (log ndenotes logarithmic running time (ndenotes linear running time ( log ndenotes log-linear running time (nkdenotes polynomial running time notice that is constant (cndenotes exponential running time here constant is being raised to power based on the size of the input constant complexity this indicates that the asymptotic complexity is independent of the inputs there are very few interesting programs in this classbut all programs have pieces (for example finding out the length of python list or multiplying two floating point numbersthat fit into this class constant running time does not imply that there are no loops or recursive calls in the codebut it does imply that the number of iterations or recursive calls is independent of the size of the inputs logarithmic complexity such functions have complexity that grows as the log of at least one of the inputs binary searchfor exampleis logarithmic in the length of the list being searched (we will look at binary search and analyze its complexity in the next by the waywe don' care about the base of the logsince the difference between using one base and another is merely constant multiplicative factor for exampleo(log ( ) (log ( )*log ( )there are lots of interesting functions with logarithmic complexity consider the more pedantic members of the computer science community use big thetathrather than big for this |
4,098 | def inttostr( )"""assumes is nonnegative int returns decimal string representation of ""digits ' if = return ' result 'while result digits[ % result // return result since there are no function or method calls in this codewe know that we only have to look at the loops to determine the complexity class there is only one loopso the only thing that we need to do is characterize the number of iterations that boils down to the number of times one can divide by sothe complexity of inttostr is (log( )what about the complexity of def adddigits( )"""assumes is nonnegative int returns the sum of the digits in ""stringrep inttostr(nval for in stringrepval +int(creturn val the complexity of converting to string is (log( )and inttostr returns string of length (log( )the for loop will be executed (len(stringrep)timesi (log( )times putting it all togetherand assuming that character representing digit can be converted to an integer in constant timethe program will run in time proportional to (log( ) (log( ))which makes it (log( )linear complexity many algorithms that deal with lists or other kinds of sequences are linear because they touch each element of the sequence constant (greater than number of times considerfor exampledef adddigits( )"""assumes is str each character of which is decimal digit returns an int that is the sum of the digits in ""val for in sval +int(creturn val this function is linear in the length of si (len( ))--again assuming that character representing digit can be converted to an integer in constant time of coursea program does not need to have loop to have linear complexity |
4,099 | simplistic introduction to algorithmic complexity consider def factorial( )"""assumes that is positive int returns !""if = return elsereturn *factorial( - there are no loops in this codeso in order to analyze the complexity we need to figure out how many recursive calls get made the series of calls is simply factorial( )factorial( - )factorial( - )factorial( the length of this seriesand thus the complexity of the functionis (xthus far in this we have looked only at the time complexity of our code this is fine for algorithms that use constant amount of spacebut this implementation of factorial does not have that property as we discussed in each recursive call of factorial causes new stack frame to be allocatedand that frame continues to occupy memory until the call returns at the maximum depth of recursionthis code will have allocated stack framesso the space complexity is (xthe impact of space complexity is harder to appreciate than the impact of time complexity whether program takes one minute or two minutes to complete is quite visible to its userbut whether it uses one megabyte or two megabytes of memory is largely invisible to users this is why people typically give more attention to time complexity than to space complexity the exception occurs when program needs more space than is available in the main memory of the machine on which it is run log-linear complexity this is slightly more complicated than the complexity classes we have looked at thus far it involves the product of two termseach of which depends upon the size of the inputs it is an important classbecause many practical algorithms are log-linear the most commonly used log-linear algorithm is probably merge sortwhich is ( log( ))where is the length of the list being sorted we will look at that algorithm and analyze its complexity in the next polynomial complexity the most commonly used polynomial algorithms are quadratici their complexity grows as the square of the size of their input considerfor examplethe function in figure which implements subset test |
Subsets and Splits