id
int64
0
25.6k
text
stringlengths
0
4.59k
19,700
notice how this pattern avoids processing the sentinel item the first item is retrieved before the loop starts this is sometimes called the priming readas it gets the process started if the first item is the sentinelthe loop immediately terminates and no data is processed otherwisethe item is processed and the next one...
19,701
loop structures and booleans valid numberpositive or negative of coursethis is impossible as long as we restrict ourselves to working with numbers no matter what number or range of numbers we pick as sentinelit is always possible that some data set may contain such number in order to have truly unique sentinelwe need t...
19,702
enter number to quit> enter number to quit> enter number to quit> enter number to quit>- enter number to quit>- enter number to quit> enter number to quit>the average of the numbers is we finally have an excellent solution to our original problem you should study this solution so that you can incorporate these techniqu...
19,703
loop structures and booleans gets the next line from file as string at the end of the filereadline(returns an empty stringwhich we can use as sentinel value here is general pattern for an end-of-file loop using readline()in python line infile readline(while line !""process line line infile readline(at first glanceyou m...
19,704
of our file averaging problem slightly this timeinstead of typing the numbers into the file oneper-linewe'll allow any number of values on line when multiple values appear on linethey will be separated by commas at the top levelthe basic algorithm will be some sort of file-processing loop that computes running sum and ...
19,705
loop structures and booleans main(as you can seethe loop that processes the numbers in line is indented inside of the file processing loop the outer while loop iterates once for each line of the file on each iteration of the outer loopthe inner for loop iterates as many times as there are numbers on that line when the ...
19,706
and or the and of two expressions is true exactly when both of the expressions are true we can represent this definition in truth table and in this tablep and represent smaller boolean expressions since each expression has two possible valuesthere are four possible combinations of valueseach shown as one row in the tab...
19,707
loop structures and booleans ( or ((not band )unlike arithmetichowevermost people don' tend to know or remember the precedence rules for booleans suggest that you always parenthesize your complex expressions to prevent confusion now that we have some boolean operatorswe are ready to return to our example problem to tes...
19,708
( > and > or ( > and > do you see how this expression worksit basically says the game is over when team has won (scored at least and leading by at least or when team has won here is another way to do it( > or > and abs( > this version is bit more succinct it states that the game is over when one of the teams has reache...
19,709
notice how the operator changes between and and or when the not is pushed into an expression one application of boolean algebra is the analysis and simplification of boolean expressions inside of programs for examplelet' go back to the racquetball game one more time abovewe developed loop condition for continuing the g...
19,710
repeat get number from the user until number is > the idea here is that the loop keeps getting inputs until the value is acceptable the flowchart depicting this design in shown in figure notice how this algorithm contains loop where the condition test comes after the loop body this is post-test loop post-test loop must...
19,711
loop structures and booleans the first line may look bit strange to you remember that while loop continues as long as the expression in the loop heading evaluates to true since true is always truethis appears to be an infinite loop howeverwhen the value of is non-negativethe break statement executeswhich terminates the...
19,712
figure shows flowchart of this approach to sentinel loops you can see that this implementation is faithful to the first rule of sentinel loopsavoid processing the sentinel value get next data item item is the sentinel yes no process the item figure loop-and- -half implementation of sentinel loop pattern the choice of w...
19,713
you already know that python has bool type actuallythis is fairly recent addition to the language (version before thatpython just used the ints and to represent true and false in factthe bool type is just "specialint where the values of and print as false and true you can test this out by evaluating the expression true...
19,714
of wasthat is what is returned if turns out to be truethen the truth or falsity of the whole expression turns on the result of simply returning guarantees that if is truethe whole result is trueand if is falsethe whole result is false similar reasoning can be used to show that the description of or is faithful to the l...
19,715
loop structures and booleans here boolean condition is being used to decide how to set string variable if the user just hits ans will be an empty stringwhich python interprets as false in this casethe empty string will be replaced by "vanillain the else clause the same idea can be more succinctly coded by treating the ...
19,716
nonstandard loop structures such as loop-and- -half can be built using while loop having loop condition of true and using break statement to provide loop exit python boolean operators and and or employ short-circuit evaluation they also have operational definitions that allow them to be used in certain decision context...
19,717
priming read is part of the pattern for (nainteractive loop bend-of-file loop csentinel loop dinfinite loop what statement can be executed in the body of loop to cause it to terminateaif binput cbreak dexit which of the following is not valid rule of boolean algebraa(true or =true (false and =false cnot( and =not(aand ...
19,718
write while loop fragment that calculates the following values(asum of the first counting numbers (bsum of the first odd numbers (csum of series of numbers entered by the user until the value is entered note should not be part of the sum (dthe number of times whole number can be divided by (using integer divisionbefore...
19,719
modify the previous program to find every prime number less than or equal to the goldbach conjecture asserts that every even number is the sum of two prime numbers write program that gets number from the userchecks to make sure that it is evenand then finds two prime numbers that sum to the number the greatest common d...
19,720
compute the endpoints of the regression line spanning the window after the line is drawnthe program will pause for another mouse click before closing the window and quitting
19,721
loop structures and booleans
19,722
simulation and design objectives to understand the potential applications of simulation as way to solve real-world problems to understand pseudo random numbers and their application in monte carlo simulations to understand and be able to apply top-down and spiral design techniques in writing complex programs to underst...
19,723
simulation and design simulation problem susan computewell' frienddenny dibblebitplays racquetball over years of playinghe has noticed strange quirk in the game he often competes with players who are just little bit better than he is in the processhe always seems to get thumpedlosing the vast majority of matches this h...
19,724
output the program will provide series of initial prompts such as the followingwhat is the prob player wins servewhat is the prob player wins servehow many games to simulatethe program will print out nicely formatted report showing the number of games simulated and the number of wins and winning percentage for each pla...
19,725
simulation and design python provides library module that contains number of useful functions for generating pseudo random numbers the functions in this module derive an initial seed value from the date and time when the module is loadedso you get different seed value each time the program is run this means that you wi...
19,726
random( random( random( random( the name of the module (randomis the same as the name of the functionwhich gives rise to the funny-looking import line our racquetball simulation can make use of the random function to determine whether or not player wins serve let' look at specific example suppose player' service probab...
19,727
simulation and design top-level design top-down design is easier to illustrate than it is to define let' give it try on our racquetball simulation and see where it takes us as alwaysa good start is to study the program specification in very broad brush strokesthis program follows the basic inputprocessoutput pattern we...
19,728
supposed to simulate and what the values of proba and probb should be for those simulations these three values willin sensebe inputs to the function what information do you need to get back from your friendwellin order to finish out the program (print reportyou need to know how many games were won by player and how man...
19,729
main winsa winsb proba probb printintro getinputs proba probb winsa winsb simngames printsummary figure first-level structure chart for racquetball simulation characteristics of something and ignoring other details is called abstraction abstraction is the fundamental tool of design you might view the entire process of ...
19,730
values represent the main concern here is to make sure the values are returned in the correct order to match with the interface we established between getinputs and main designing simngames now that we are getting some experience with the top-down design techniquewe are ready to try our hand at the real problemsimngame...
19,731
def simngames(nprobaprobb)simulates games and returns winsa and winsb winsa winsb for in range( )scoreascoreb simonegame(probaprobbmain winsa winsb proba probb printintro getinputs proba probb winsa winsb simngames printsummary proba probb scorea scoreb simonegame figure level structure chart for racquetball simulation...
19,732
of indefinite loop structurewe don' know how many rallies it will take before one of the players gets to the loop just keeps going until the game is over along the waywe need to keep track of the score( )and we also need to know who is currently serving the scores will probably just be couple of int-valued accumulators...
19,733
main winsa winsb proba probb printintro getinputs proba probb winsa winsb simngames printsummary proba probb scorea scoreb simonegame scorea scoreb true|false gameover figure level structure chart for racquetball simulation if serving =" "if random(probaa wins the serve scorea scorea elsea loses the serve serving "bof ...
19,734
of the simulation as they were laid out putting the function togetherhere is the resultdef simonegame(probaprobb)scorea scoreb serving "awhile not gameover(scoreascoreb)if serving =" "if random(probascorea scorea elseserving "belseif random(probbscoreb scoreb elseserving "areturn scoreascoreb finishing up whewwe have j...
19,735
probaprobbn getinputs(winsawinsb simngames(nprobaprobbprintsummary(winsawinsbdef printintro()print("this program simulates game of racquetball between two"print('players called "aand "bthe abilities of each player is'print("indicated by probability ( number between and that"print("the player wins the point when serving...
19,736
elseserving "belseif random(probbscoreb scoreb elseserving "areturn scoreascoreb def gameover(ab) and represent scores for racquetball game returns true if the game is overfalse otherwise return == or == def printsummary(winsawinsb)prints summary of wins for each player winsa winsb print("\ngames simulated:"nprint("win...
19,737
simulation and design thoughthings probably won' go quite so smoothly stay with it--the more you do itthe easier it will get initiallyyou may think writing all of those functions is lot of trouble the truth isdeveloping any sophisticated system is virtually impossible without modular approach keep at itand soon express...
19,738
import rball rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( rball simonegame ( notice that when the probabilities are equalthe scores are close when the probabilities are farther apartthe game is ...
19,739
simulation and design the player wins the point when serving player always has the first serve what is the prob player wins serve what is the prob player wins serve how many games to simulate games simulated wins for ( %wins for ( %even though there is only small difference in abilitydenny should win only about one in ...
19,740
scorea scoreb serving "afor in range( )if serving =" "if random( scorea scorea elseserving "belseif random( scoreb scoreb elseserving "aprint(scoreascorebif __name__ ='__main__'simonegame(you can see that have added print statement at the bottom of the loop printing out the scores as we go along allows us to see that t...
19,741
spiral development is particularly useful when dealing with new or unfamiliar features or technologies it' helpful to "get your hands dirtywith quick prototype just to see what you can do as novice programmereverything may seem new to youso prototyping might prove useful if full-blown top-down design does not seem to b...
19,742
exercises review questions true/false computers can generate truly random numbers the python random function returns pseudo random int top-down design is also called stepwise refinement in top-down designthe main algorithm is written in terms of functions that don' yet exist the main function is at the top of functiona...
19,743
the initial version of system used in spiral development is called astarter kit bprototype cmock-up dbeta-version in the racquetball simulationwhat data type is returned by the gameover functionabool bint cstring dfloat how is percent sign indicated in string formatting templateab\ % \% the easiest place in system stru...
19,744
design and implement simulation of the game of volleyball normal volleyball is played like racquetballin that team can only score points when it is serving games are played to but must be won by at least two points most sanctioned volleyball is now played using rally scoring in this systemthe team that wins rally is aw...
19,745
monte carlo techniques can be used to estimate the value of pi suppose you have round dart board that just fits inside of square cabinet if you throw darts randomlythe proportion that hit the dart board vs those that hit the cabinet (in the corners not covered by the boardwill be determined by the relative area of the ...
19,746
(advancedhere is puzzle problem that can be solved with either some fancy analytic geometry (calculusor (relativelysimple simulation suppose you are located at the exact center of cube if you could look all around you in every directioneach wall of the cube would occupy of your field of vision suppose you move toward o...
19,747
simulation and design
19,748
defining classes objectives to appreciate how defining new classes can provide structure for complex program to be able to read and write python class definitions to understand the concept of encapsulation and how it contributes to building modular and maintainable programs to be able to write programs involving simple...
19,749
defining classes to take now familiar examplea circle object will have instance variables such as centerwhich remembers the center point of the circleand radiuswhich stores the length of the circle' radius the methods of the circle will need this data to perform actions the draw method examines the center and radius to...
19,750
for those who know little bit of calculusit' not hard to derive formula that gives the position of our cannonball at any given moment in its flight rather than take the calculus approachhoweverour program will use simulation to track the cannonball moment by moment using just bit of simple trigonometry to get startedal...
19,751
calculating the initial position for the cannonball is also easy it will start at distance and height we just need couple of assignment statements xpos ypos next we need to calculate the and components of the initial velocity we'll need little highschool trigonometry (seethey told you you' use that some day if we consi...
19,752
now we arrive at the crux of the simulation each time we go through the loopwe want to update the state of the cannonball to move it time seconds farther in its flight let' start by considering movement in the horizontal direction since our specification says that we can ignore wind resistancethe horizontal speed of th...
19,753
vel eval(input("enter the initial velocity (in meters/sec)") eval(input("enter the initial height (in meters)")time eval(input("enter the time interval between position calculations")convert angle to radians theta radians(angleset the initial position and velocities in and directions xpos ypos xvel vel cos(thetayvel ve...
19,754
this second version of the main algorithm is certainly more concise the number of variables has been reduced to eightsince theta and yvel have been eliminated from the main algorithm do you see where they wentthe value of theta is only needed locally inside of getxycomponents similarlyyvel is now local to updatecannonb...
19,755
defining classes how many sides it has its current value when new msdie is createdwe specify how many sides it will haven we can then operate on the die through three provided methodsrollto set the die to random value between and ninclusivesetvalueto set the die to specific value ( cheat)and getvalueto see what the cur...
19,756
def __init__(selfsides)self sides sides self value def roll(self)self value randrange( ,self sides+ def getvalue(self)return self value def setvalue(selfvalue)self value value as you can seea class definition has simple formclass each method definition looks like normal function definition placing the function inside c...
19,757
figure illustrates the method-calling sequence for this example notice how the method is called with one parameter (the value)but the method definition has two parametersdue to self generally speakingwe would say setvalue requires one parameter the self parameter in the definition is bookkeeping detail some languages d...
19,758
print die getvalue( the call to the constructor sets the instance variable die value to the next line prints out this value the value set by the constructor persists as part of the objecteven though the constructor is over and done with similarlyexecuting die setvalue( changes the object by setting its value to when th...
19,759
def gety(self)return self ypos finallywe come to the update method this method takes single normal parameter that represents an interval of time we need to update the state of the projectile to account for the passage of that much time here' the codedef update(selftime)self xpos self xpos time self xvel yvel self yvel ...
19,760
eval(input("enter the launch angle (in degrees)") eval(input("enter the initial velocity (in meters/sec)") eval(input("enter the initial height (in meters)") eval(input("enter the time interval between position calculations")return , , , def main()anglevelh time getinputs(cball projectile(anglevelh while cball gety(> c...
19,761
defining classes class studentdef __init__(selfnamehoursqpoints)self name name self hours float(hoursself qpoints float(qpointsnotice that have used parameter names that match the instance variable names this looks bit strange at firstbut it is very common style for this sort of class have also floated the values of ho...
19,762
get the file name from the user open the file for reading set best to be the first student for each student in the file if gpa(best gpa(set best to print out information about best the completed program looks like thisgpa py program to find student with highest gpa class studentdef __init__(selfnamehoursqpoints)self na...
19,763
set best to the record for the first student in the file best makestudent(infile readline()process subsequent lines of the file for line in infileturn the line into student record makestudent(lineif this student is best so farremember it if gpa(best gpa()best infile close(print information about the best student print(...
19,764
objects and encapsulation encapsulating useful abstractions hopefullyyou are seeing how defining new classes like projectile and student can be good way to modularize program once we identify some useful objectswe can write an algorithm using those objects and push the implementation details into suitable class definit...
19,765
defining classes putting classes in modules often well-defined class or set of classes provides useful abstractions that can be leveraged in many different programs for examplewe might want to turn our projectile class into its own module file so that it can be used in other programs in doing soit would be good idea to...
19,766
flight of projectiles ""from math import sincosradians class projectile"""simulates the flight of simple projectiles near the earth' surfaceignoring wind resistance tracking is done in two dimensionsheight (yand distance ( ""def __init__(selfanglevelocityheight)"""create projectile with given launch angleinitial veloci...
19,767
defining classes you might try help(projectileto see how the complete documentation looks for this module working with multiple modules our main program can now simply import from the projectile module in order to solve the original problem cball py from projectile import projectile def getinputs() eval(input("enter th...
19,768
widgets one very common use of objects is in the design of graphical user interfaces (guisback in we talked about guis being composed of visual interface objects called widgets the entry object defined in our graphics library is one example of widget now that we know how to define new classeswe can create our own custo...
19,769
can do is find out where the mouse was clicked after the click has already completed neverthelesswe can make usefulif less prettybutton class our buttons will be rectangular regions in graphics window where user clicks can influence the behavior of the running application we will need to create buttons and determine wh...
19,770
def deactivate(self)"sets this button to 'inactiveself label setfill('darkgrey'self rect setwidth( self active false of coursethe main point of button is being able to determine if it has been clicked let' try to write the clicked method as you knowthe graphics package provides getmouse method that returns the point wh...
19,771
button py from graphics import class button""" button is labeled rectangle in window it is activated or deactivated with the activate(and deactivate(methods the clicked(pmethod returns true if the button is active and is inside it ""def __init__(selfwincenterwidthheightlabel)""creates rectangular buttonegqb button(mywi...
19,772
def deactivate(self)"sets this button to 'inactiveself label setfill('darkgrey'self rect setwidth( self active false you should study the constructor in this class to make sure you understand all of the instance variables and how they are initialized button is positioned by providing center pointwidthand height other i...
19,773
of length ""first define some standard values self win win save this for drawing pips later self background "whitecolor of die face self foreground "blackcolor of the pips self psize size radius of each pip hsize size half the size of the die offset hsize distance from center to outer pips create square for the face cx...
19,774
self pip setfill(self backgroundself pip setfill(self backgroundself pip setfill(self backgroundself pip setfill(self backgroundself pip setfill(self backgroundself pip setfill(self backgroundturn correct pips on if value = self pip setfill(self foregroundelif value = self pip setfill(self foregroundself pip setfill(se...
19,775
not part of the original specification this method is just helper function that executes the four lines of code necessary to draw each of the seven pips since this is function that is only useful within the dieview classit is appropriate to make it class method inside the constructorit is invoked by lines such as self ...
19,776
die setvalue(value quitbutton activate(pt win getmouse(close up shop win close(main(notice that near the top of the program have built the visual interface by creating the two dieviews and two buttons to demonstrate the activation feature of buttonsthe roll button is initially activebut the quit button is left deactiva...
19,777
correctly designed classes provide encapsulation the internal details of an object are hidden inside the class definition so that other portions of the program do not need to know how an object is implemented this separation of concerns is programming convention in pythonthe instance variables of an object should only ...
19,778
within method definitionthe instance variable could be accessed via which expressionax bself cself[xdself getx( python convention for defining methods that are "privateto class is to begin the method name with "privateba pound sign (#can underscore (_da hyphen (- the term applied to hiding details inside class definiti...
19,779
def clown(selfx)print "clowning:" print self value return self value def main()print "clowning around now bozo( bozo( print clown( print clown( clown( )main(programming exercises modify the cannonball simulation from the so that it also calculates the maximum height achieved by the cannonball use the button class discu...
19,780
extend the previous exercise by implementing an addlettergrade method this is similar to addgrade except that it accepts letter grade as string (instead of gradepointuse the updated class to improve the gpa calculator by allowing the entry of letter grades write modified button class that creates circular buttons call ...
19,781
notea method named __str__ is special in python if asked to convert an object into stringpython uses this methodif it' present for examplec card( ," "print will print "ace of spades test your card class with program that prints out randomly generated cards and the associated blackjack value where is number supplied by ...
19,782
use your class to write program that draws face and provides the user with buttons to change the facial expression modify the face class from the previous problem to include move method similar to other graphics objects using the move methodcreate program that makes face bounce around in window (see programming exercis...
19,783
defining classes noteyour class might also use some internal helper methods to do such things as compute the slope of the regression line
19,784
data collections objectives to understand the use of lists (arraysto represent collection of related data to be familiar with the functions and methods available for manipulating python lists to be able to write programs that use lists to manage collection of information to be able to write programs that use lists and ...
19,785
in this you will learn techniques for writing programs that manipulate collections like these let' start with simple examplea collection of numbers back in we wrote simple but useful program to compute the mean (averageof set of numbers entered by the user just to refresh your memory (as if you could forget it)here is ...
19,786
let' take simple example if we again use the values and the mean of this data (xis so the numerator of the fraction is computed as ( ) ( ) ( ) ( ) ( ) finishing out the calculation gives us ss - the standard deviation is about you can see how the first step of this calculation uses both the mean (which can' be computed...
19,787
by using numbers as subscriptsmathematicians are able to succinctly summarize computations over items in the sequence using subscript variables for examplethe sum of the sequence is written using standard summation notation as - si = similar idea can be applied to computer programs with listwe can use single variable t...
19,788
except for the last (membership check)these are the same operations that we used before on strings the membership operation can be used to see if certain value appears anywhere in sequence here are couple of quick examples checking for membership in lists and stringlst [ , , , in lst true in lst false ans 'yans in 'yyt...
19,789
in the last exampleempty is list containing no items at all--an empty list list of identical items can be created using the repetition operator this example creates list containing zeroeszeroes [ often lists are built up one piece at time using the append method here is fragment of code that fills list with positive nu...
19,790
notice that del is not list methodbut built-in operation that can be used on list items as you can seepython lists provide very flexible mechanism for handling arbitrarily large sequences of data using lists is easy if you keep these basic principles in minda list is sequence of items stored as single object items in l...
19,791
data collections def mean(nums)sum for num in numssum sum num return sum len(numsnotice how the average is computed and returned in the last line of this function the len operation returns the length of listwe don' need separate loop accumulator to determine how many numbers there are with these two functionsour origin...
19,792
pack isby definitionthe median there is just one small complication if we have an even number of valuesthere is no exact middle number in that casethe median is determined by averaging the two middle values so the median of and is ( )/ in pseudocode our median algorithm looks like thissort the numbers into ascending or...
19,793
print("\nthe mean is"xbarprint("the standard deviation is"stdprint("the median is"medmany computational tasks from assigning grades to monitoring flight systems on the space shuttle require some sort of statistical analysis by using the if __name__ ='__main__techniquewe can make our code useful as stand-alone program a...
19,794
elsemedian nums[midposreturn median def main()print("this program computes meanmedian and standard deviation "data getnumbers(xbar mean(datastd stddev(dataxbarmed median(dataprint("\nthe mean is"xbarprint("the standard deviation is"stdprint("the median is"medif __name__ ='__main__'main( lists of records all of the list...
19,795
data collections objects from the filedef readstudents(filename)infile open(filename' 'students [for line in infilestudents append(makestudent(line)infile close(return students this function first opens the file for reading and then reads line by lineappending student object to the students list for each line of the fi...
19,796
as you can seepython gives us an error message because it does not know how our student objects should be ordered if you think about itthat makes sense we have not defined any implicit ordering for studentsand we might want to arrange them in different order for different purposes in this examplewe want them ranked by ...
19,797
data collections from gpa import studentmakestudent def readstudents(filename)infile open(filename' 'students [for line in infilestudents append(makestudent(line)infile close(return students def writestudents(studentsfilename)outfile open(filename' 'for in studentsprint("{ }\ { }\ { }format( getname() gethours() getqpo...
19,798
in our previous versionthe pips were created with this sequence of statements inside of __init__self pip self __makepip(cx-offsetcy-offsetself pip self __makepip(cx-offsetcyself pip self __makepip(cx-offsetcy+offsetself pip self __makepip(cxcyself pip self __makepip(cx+offsetcy-offsetself pip self __makepip(cx+offsetcy...
19,799
data collections for pip in self pipspip setfill(self backgroundsee how these two lines of code loop through the entire collection of pips to change their colorthis required seven lines of code in the previous version using separate instance variables similarlywe can turn set of pips back on by indexing the appropriate...