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 prin...
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...
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 an...
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 ...
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 str...
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 ...
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...
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 sq...
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...
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 th...
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 lea...
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 con...
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 ...
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 st...
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 functio...
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 followin...
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 v...
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 ...
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...
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 doe...
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 programmerswr...
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 an...
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' ...
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 ...
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 fact...
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...
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 bunn...
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 n...
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 ...
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 ispa...
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 nu...
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 ...
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 sta...
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 n...
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 e...
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...
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' ( ...
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 % = a...
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...
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 equal...
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...
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 con...
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...
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 prod...
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 ...
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 se...
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 th...
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 gre...
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 t...
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 ...
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 d...
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 con...
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...
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 th...
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 e...
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 ...
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 you...
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 radia...
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' car...
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' hav...
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 reve...
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...
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 fi...
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 alre...
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 t...
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 t...
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...
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 ...
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 lengt...
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 t...
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 programmi...
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...
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 ...
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 ...
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 fi...
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 bio...
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 lastn...
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 ...
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 fro...
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__ meth...
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 coupl...
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 diff...
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...
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 ...
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'...
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...
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 v...
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 t...
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 i...
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 s...
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 teasermonth...
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 cos...
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 airpl...
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 arithmet...
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 o...
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 appr...
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 ex...
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 th...
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...
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(...