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 is read the loop test at the top ensures this next item is not the sentinel before processing it when the sentinel is reachedthe loop terminates we can apply the sentinel pattern to our number averaging problem the first step is to pick sentinel suppose we are using the program to average exam scores in that casewe can safely assume that no score will be below the user can enter negative number to signal the end of the data combining the sentinel loop with the two accumulators from the interactive loop version yields this program average py def main()sum count eval(input("enter number (negative to quit>")while > sum sum count count eval(input("enter number (negative to quit>")print("\nthe average of the numbers is"sum countmain( have changed the prompt so that the user knows how to signal the end of the data notice that the prompt is identical at the priming read and the bottom of the loop body now we have useful form of the program here it is in actionenter number (negative to quit> enter number (negative to quit> enter number (negative to quit> enter number (negative to quit> enter number (negative to quit> enter number (negative to quit>- the average of the numbers is this version provides the ease of use of the interactive loop without the hassle of having to type "yesall the time the sentinel loop is very handy pattern for solving all sorts of data processing problems it' another cliche that you should commit to memory this sentinel loop solution is quite goodbut there is still limitation the program can' be used to average set of numbers containing negative as well as positive values let' see if we can' generalize the program bit what we need is sentinel value that is distinct from any possible |
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 to broaden the possible inputs suppose that we get the input from the user as string we can have distinctivenon-numeric string that indicates the end of the inputall others would be converted into numbers and treated as data one simple solution is to have the sentinel value be an empty string rememberan empty string is represented in python as "(quotes with no space betweenif the user types blank line in response to input (just hits )python returns an empty string we can use this as simple way to terminate input the design looks like thisinitialize sum to initialize count to input data item as stringxstr while xstr is not empty convert xstr to numberx add to sum add to count input next data item as stringxstr output sum count comparing this to the previous algorithmyou can see that converting the string to number has been added to the processing section of the sentinel loop translating it into python yields this programaverage py def main()sum count xstr input("enter number to quit>"while xstr !"" eval(xstrsum sum count count xstr input("enter number to quit>"print("\nthe average of the numbers is"sum countmain(this code does not turn the input into number (via evaluntil after it has checked to make sure the input was not the sentinel (""here is an example runshowing that it is now possible to average arbitrary sets of numbers |
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 techniques into your own programs file loops one disadvantage of all the averaging programs presented so far is that they are interactive imagine you are trying to average numbers and you happen to make typo near the end with our interactive programyou will need to start all over again better approach to the problem might be to type all of the numbers into file the data in the file can be perused and edited before sending it to program that generates report this file-oriented approach is typically used for data processing applications back in we looked at reading data from files by using the file object as sequence in for loop we can apply this technique directly to the number averaging problem assuming that the numbers are typed into file one per linewe can compute the average with this program average py def main()filename input("what file are the numbers in"infile open(filename,' 'sum count for line in infilesum sum eval(linecount count print("\nthe average of the numbers is"sum countmain(in this codethe loop variable line iterates through the file as sequence of lineseach line is converted to number and added to the running sum many programming languages do not have special mechanism for looping through files like this in these languagesthe lines of file can be read one at time using form of sentinel loop we can illustrate this method in python by using readline(rememberthe readline(method |
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 may be concerned that this loop stops prematurely if it encounters an empty line in the file this is not the case remembera blank line in text file contains single newline character ("\ ")and the readline method includes the newline character in its return value since "\ !""the loop will continue here is the code that results from applying the end-of-file sentinel loop to our number averaging problemaverage py def main()filename input("what file are the numbers in"infile open(filename,' 'sum count line infile readline(while line !""sum sum eval(linecount count line infile readline(print("\nthe average of the numbers is"sum countmain(obviouslythis version is not quite as concise as the version using the for loop in pythonyou might as well use the latterbut it is still good to know about end-of-file loops in case you're stuck programming in less elegant language nested loops in the last you saw how control structures such as decisions and loops could be nested inside one another to produce sophisticated algorithms one particularly usefulbut somewhat tricky technique is the nesting of loops let' take look at an example program how about one last version of our number averaging problemi promise this is the last time 'll use this example suppose we modify the specification until |
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 count for practicelet' use an end-of-file loop here is the code comprising the top-level loopsum count line infile readline(while line !""update sum and count for values in line line infile readline(print("\nthe average of the numbers is"sum countnow we need to figure out how to update the sum and count in the body of the loop since each individual line of the file contains one or more numbers separated by commaswe can split the line into substringseach of which represents number then we need to loop through these substringsconvert each to numberand add it to sum we also need to add to count for each number here is code fragment that processes linefor xstr in line split(",")sum sum eval(xstrcount count + notice that the iteration of the for loop in this fragment is controlled by the value of linewhich just happens to be the loop-control variable for the file-processing loop we outlined above knitting these two loops togetherhere is our programaverage py def main()filename input("what file are the numbers in"infile open(filename,' 'sum count line infile readline(while line !""update sum and count for values in line for xstr in line split(",")sum sum eval(xstrcount count line infile readline(print("\nthe average of the numbers is"sum count |
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 inner loop finishesthe next line of the file is readand the outer loop goes through its next iteration the individual fragments of this problem are not complex when taken separatelybut the final result is fairly intricate the best way to design nested loops is to follow the process we did here first design the outer loop without worrying about what goes inside then design what goes insideignoring the outer loop(sfinallyput the pieces togethertaking care to preserve the nesting if the individual loops are correctthe nested result will work just finetrust it with little practiceyou'll be implementing double-even triple-nested loops with ease computing with booleans we now have two control structuresif and whilethat use conditionswhich are boolean expressions conceptuallya boolean expression evaluates to one of two valuesfalse or true in pythonthese values are represented by the literals false and true so farwe have used simple boolean expressions that compare two values ( while > boolean operators sometimes the simple conditions that we have been using do not seem expressive enough for examplesuppose you need to determine whether two point objects are in the same position--that isthey have equal coordinates and equal coordinates one way of handling this would be nested decision if getx(= getx()if gety(= gety()points are the same elsepoints are different elsepoints are different you can see how awkward this is instead of working around this problem with decision structureanother approach would be to construct more complex expression using boolean operations like most programming languagespython provides three boolean operatorsandorand not let' take look at these three operators and then see how they can be used to simplify our problem the boolean operators and and or are used to combine two boolean expressions and produce boolean result |
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 table the last column gives the value of and for each possible combination by definitionthe and is true only in the case where both and are true the or of two expressions is true when either expression is true here is the truth table defining orp or the only time the or is false is when both expressions are false notice especially that or is true when both expressions are true this is the mathematical definition of orbut the word "oris sometimes used in an exclusive sense in everyday english if your mom said that you could have cake or cookies for dessertshe would probably scold you for taking both the not operator computes the opposite of boolean expression it is unary operatormeaning that it operates on single expression the truth table is very simple not using boolean operatorsit is possible to build arbitrarily complex boolean expressions as with arithmetic operatorsthe exact meaning of complex expression depends on the precedence rules for the operators consider this expressiona or not and how should this be evaluatedpython follows standard convention that the order of precedence from high to low is notfollowed by andfollowed by or so the expression would be equivalent to this parenthesized version |
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 test for the co-location of two pointswe could use an and operation if getx(= getx(and gety(= gety()points are the same elsepoints are different here the entire expression will only be true when both of the simple conditions are true this ensures that both the and coordinates have to match for the points to be the same obviouslythis is much simpler and clearer than the nested ifs from the previous version let' look at slightly more complex example in the next we will develop simulation for the game of racquetball part of the simulation will need to determine when game has ended suppose that scorea and scoreb represent the scores of two racquetball players the game is over as soon as either of the players has reached points here is boolean expression that is true when the game is overscorea = or scoreb = when either score reaches one of the two simple conditions becomes trueandby definition of orthe entire boolean expression is true as long as both conditions remain false (neither player has reached the entire expression is false our simulation will need loop that continues as long as the game is not over we can construct an appropriate loop condition by taking the negation of the game-over condition while not (scorea = or scoreb = )continue playing we can also construct more complex boolean expressions that reflect different possible stopping conditions some racquetball players play shutouts (sometimes called skunkfor these playersa game also ends when one of the players reaches and the other has not yet scored point for brevityi'll use for scorea and for scoreb here is an expression for game-over when shutouts are includeda = or = or ( = and = or ( = and = do you see how have added two more situations to the original conditionthe new parts reflect the two possible ways shutout can occurand each requires checking both scores the result is fairly complex expression while we're at itlet' try one more example suppose we were writing simulation for volleyballrather than racquetball traditional volleyball does not have shutoutsbut it requires team to win by at least two points if the score is to or even to the game continues let' write condition that computes when volleyball game is over here' one approach |
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 reached winning total and the difference in the scores is at least remember that abs returns the absolute value of an expression boolean algebra all decisions in computer programs boil down to appropriate boolean expressions the ability to formulatemanipulateand reason with these expressions is an important skill for programmers and computer scientists boolean expressions obey certain algebraic laws similar to those that apply to numeric operations these laws are called boolean logic or boolean algebra let' look at few examples the following table shows some rules of algebra with their correlates in boolean algebraalgebra * = * = + = boolean algebra and false =false and true = or false = from these examplesyou can see that and has similarities to multiplicationand or has similarities to additionwhile and correspond to false and true here are some other interesting properties of boolean operations anything ored with true is just true or true =true both and and or distribute over each other or ( and =( or band ( or ca and ( or =( and bor ( and ca double negative cancels out not(not = the next two identities are known as demorgan' laws not( or =(not aand (not bnot( and =(not aor (not |
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 game that looked like thiswhile not (scorea = or scoreb = )continue playing you can read this condition as something likewhile it is not the case that player has or player has continue playing we're pretty sure that' correctbut negating complex conditions like this can be somewhat awkwardto say the least using little boolean algebrawe can transform this result applying demorgan' lawwe know that the expression is equivalent to this(not scorea = and (not scoreb = rememberwe have to change the or to and when "distributingthe not this condition is no better than the firstbut we can go one step farther by pushing the nots into the conditions themselves while scorea ! and scoreb ! continue playing now we have version that is much easier to understand this reads simply as while player has not reached and player has not reached continue playing this particular example illustrates generally useful approach to loop conditions sometimes it' easier to figure out when loop should stoprather than when the loop should continue in that casesimply write the loop termination condition and then put not in front of it an application or two of demorgan' laws can then get you to simpler but equivalent version suitable for use in while statement other common structures taken togetherthe decision structure (ifalong with pre-test loop (whileprovide complete set of control structures this means that every algorithm can be expressed using just these once you've mastered the while and the ifyou can write every conceivable algorithmin principle howeverfor certain kinds of problemsalternative structures can sometimes be convenient this section outlines some of those alternatives post-test loop suppose you are writing an input algorithm that is supposed to get non-negative number from the user if the user types an incorrect inputthe program asks for another value it continues to reprompt until the user enters valid value this process is called input validation well-engineered programs validate inputs whenever possible here is simple algorithm |
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 always execute the body of the loop at least once get number number yes no figure flowchart of post-test loop unlike some other languagespython does not have statement that directly implements post-test loop howeverthis algorithm can be implemented with while by "seedingthe loop condition for the first iteration number - start with an illegal value to get into the loop while number number eval(input("enter positive number")this forces the loop body to execute at least once and is equivalent to the post-test algorithm you might notice that this is similar to the structure given earlier for the interactive loop pattern interactive loops are naturally suited to post-test implementation some programmers prefer to simulate post-test loop more directly by using python break statement executing break causes python to immediately exit the enclosing loop often break statement is used to leave what looks syntactically like an infinite loop here is the same algorithm implemented with breakwhile truenumber eval(input("enter positive number")if > break exit loop if number is valid |
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 loop notice that placed the break on the same line as the if this is legal when the body of the if only contains one statement it' common to see one-line if-break combination used as loop exit even this small example can be improved it would be nice if the program issued warning explaining why the input was invalid in the while version of the post-test loopthis is bit awkward we need to add an if so that the warning is not displayed for valid inputs number - start with an illegal value to get into the loop while number number eval(input("enter positive number")if number print("the number you entered was not positive"do you see how the validity check gets repeated in two placesadding warning to the version using break only requires adding an else to the existing if while truenumber eval(input("enter positive number")if > break exit loop if number is valid elseprint("the number you entered was not positive"loop and half some programmers would solve the warning problem from the previous section using slightly different style while truenumber eval(input("enter positive number")if > break loop exit print("the number you entered was not positive"here the loop exit is actually in the middle of the loop body this is called loop and half some purists frown on exits in the midst of loop like thisbut the pattern can be quite handy the loop and half is an elegant way to avoid the priming read in sentinel loop here is the general pattern of sentinel loop implemented as loop and halfwhile trueget next data item if the item is the sentinelbreak process the item |
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 whether to use break statements or not is largely matter of taste either style is acceptable one temptation that should generally be avoided is peppering the body of loop with multiple break statements the logic of loop is easily lost when there are multiple exits howeverthere are times when even this rule should be broken to provide the most elegant solution to problem boolean expressions as decisions so farwe have talked about boolean expressions only within the context of other control structures sometimesboolean expressions themselves can act as control structures in factboolean expressions are so flexible in python that they can sometimes lead to subtle programming errors consider writing an interactive loop that keeps going as long as the user response starts with " to allow the user to type either an upper or lower case responseyou could use loop like thiswhile response[ ="yor response[ =" "you must be careful not to abbreviate this condition as you might think of it in english"while the first letter is 'yor ' "the following form does not work while response[ ="yor " "in factthis is an infinite loop understanding why this condition is always true requires digging into some idiosyncrasies of python boolean expressions |
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 true we have been using the bool literals true and false to represent the boolean values true and falserespectively the python condition operators ( ==always evaluate to value of type bool howeverpython is actually very flexible about what data type can appear as boolean expression any built-in type can be interpreted as boolean for numbers (ints and floatsa zero value is considered as falseanything other than zero is taken as true you can see how value will be interpreted when used as boolean expression by explicitly converting the value to type bool here are few examplesbool( false bool( true bool( true bool("hello"true bool(""false bool([ , , ]true bool([]false as you can seefor sequence typesan empty sequence is interpreted as false whereas any nonempty sequence is taken to indicate true the flexibility of python booleans extends to the boolean operators although the main use of these operators is forming boolean expressionsthey have operational definitions that make them useful for other purposes as well this table summarizes the behavior of these operatorsoperator and or not operational definition if is falsereturn otherwisereturn if is truereturn otherwisereturn if is falsereturn true otherwisereturn false the definition of not is straightforward it might take bit of thinking to convince yourself that these descriptions of and and or faithfully reflect the truth tables you saw at the beginning of the consider the expression and in order for this to be trueboth expressions and must be true as soon as one of them is discovered to be falsethe party is over python looks at the expressions left-to-right if is falsepython should return false result whatever the false value |
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 logical definition of or given in the truth table these operational definitions show that python' boolean operators are short-circuit operators that means that true or false value is returned as soon as the result is known in an and where the first expression is false and in an or where the first expression is truepython will not even evaluate the second expression now let' take look at our infinite loop problemresponse[ ="yor "ytreated as boolean expressionthis will always evaluate to true the first thing to notice is that the boolean operator is combining two expressionsthe first is simple conditionand the second is string here is an equivalent parenthesized version(response[ =" "or (" ")by the operational description of orthis expression returns either true (returned by =when response[ is " "or " (when response[ is not " "either of these results is interpreted by python as true more logic-oriented way to think about this is to simply look at the second expression it is nonempty stringso python will always interpret it as true since at least one of the two expressions is always truethe or of the expressions must always be true as well sothe strange behavior of this example is due to some quirks in the definitions of the boolean operators this is one of the few places where the design of python has potential pitfall for the beginning programmer you may wonder about the wisdom of this designyet the flexibility of python allows for certain succinct programming idioms that many programmers find useful let' look at an example frequentlyprograms prompt users for information but offer default value for the response the default valuesometimes listed in square bracketsis used if the user simply hits the key here is an example code fragmentans input("what flavor do you want [vanilla]"if ans !""flavor ans elseflavor "vanillaexploiting the fact that the string in ans can be treated as booleanthe condition in this code can be simplified as followsans input("what flavor do you want [vanilla]"if ansflavor ans elseflavor "vanilla |
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 strings themselves as booleans and using an or ans input("what flavor do you want [vanilla]"flavor ans or "vanillathe operational definition of or guarantees that this is equivalent to the if-else version rememberany nonempty answer is interpreted as "true in factthis task can easily be accomplished in single line of code flavor input("what flavor do you want [vanilla]"or "vanillai don' know whether it' really worthwhile to save few lines of code using boolean operators this way if you like this styleby all meansfeel free to use it just make sure that your code doesn' get so tricky that others (or youhave trouble understanding it summary this has filled in details of python loops and boolean expressions here are the highlightsa python for loop is definite loop that iterates through sequence python while statement is an example of an indefinite loop it continues to iterate as long as the loop condition remains true when using an indefinite loopprogrammers must guard against the possibility of accidentally writing an infinite loop one important use for an indefinite loop is for implementing the programming pattern interactive loop an interactive loop allows portions of program to be repeated according to the wishes of the user sentinel loop is loop that handles input until special value (the sentinelis encountered sentinel loops are common programming pattern in writing sentinel loopa programmer must be careful that the sentinel is not processed loops are useful for reading files python treats file as sequence of linesso it is particularly easy to process file line-by-line using for loop in other languagesa file loop is generally implemented using sentinel loop pattern loopslike other control structurescan be nested when designing nested loop algorithmsit is best to consider the loops one at time complex boolean expressions can be built from simple conditions using the boolean operators andorand not boolean operators obey the rules of boolean algebra demorgan' laws describe how to negate boolean expressions involving and and or |
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 contexts even though python has built-in bool data typeother data types ( intmay also be used where boolean expressions are expected exercises review questions true/false python while implements definite loop the counted loop pattern uses definite loop sentinel loop asks the user whether to continue on each iteration sentinel loop should not actually process the sentinel value the easiest way to iterate through the lines of file in python is to use while loop while is post-test loop the boolean operator or returns true when both of its operands are true and ( or =( and bor ( and not( or =(not aor not( true or false multiple choice loop pattern that asks the user whether to continue on each iteration is called (nainteractive loop bend-of-file loop csentinel loop dinfinite loop loop pattern that continues until special value is input is called (nainteractive loop bend-of-file loop csentinel loop dinfinite loop loop structure that tests the loop condition after executing the loop body is called apre-test loop bloop-and- -half csentinel loop dpost-test loop |
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 not(bd(true or false=true loop that never terminates is called abusy bindefinite ctight dinfinite which line would not be found in truth table for andat bt cf df which line would not be found in truth table for orat bt cf df the term for an operator that may not evaluate one of its subexpressions is ashort-circuit bfaulty cexclusive dindefinite discussion compare and contrast the following pairs of terms(adefinite loop vs indefinite loop (bfor loop vs while loop (cinteractive loop vs sentinel loop (dsentinel loop vs end-of-file loop give truth table that shows the (booleanvalue of each of the following boolean expressionsfor every possible combination of "inputvalues hintincluding columns for intermediate expressions is helpful (anot ( and ( (not and ( (not or (not ( ( and qor ( ( or rand ( or |
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 reaching ( log nprogramming exercises the fibonacci sequence starts each number in the sequence (after the first twois the sum of the previous two write program that computes and outputs the nth fibonacci numberwhere is value entered by the user the national weather service computes the windchill index using the following formula ( ( where is the temperature in degrees fahrenheitand is the wind speed in miles per hour write program that prints nicely formatted table of windchill values rows should represent wind speed for to in mph incrementsand the columns represent temperatures from - to + in -degree increments write program that uses while loop to determine how long it takes for an investment to double at given interest rate the input will be an annualized interest rateand the output is the number of years it takes an investment to double notethe amount of the initial investment does not matteryou can use $ the syracuse (also called collatz or hailstonesequence is generated by starting with natural number and repeatedly applying the following function until reaching syr(xx/ if is even if is odd for examplethe syracuse sequence starting with is it is an open question in mathematics whether this sequence will always go to for every possible starting value write program that gets starting value from the user and then prints the syracuse sequence for that starting value positive whole number is prime if no number between and (inclusiveevenly divides write program that accepts value of as input and determines if the value is prime if is not primeyour program should quit as soon as it finds value that evenly divides |
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 divisor (gcdof two values can be computed using euclid' algorithm starting with the values and nwe repeatedly apply the formulanm mn% until is at that pointn is the gcd of the original and write program that finds the gcd of two numbers using this algorithm write program that computes the fuel efficiency of multi-leg journey the program will first prompt for the starting odometer reading and then get information about series of legs for each legthe user enters the current odometer reading and the amount of gas used (separated by spacethe user signals the end of the trip with blank line the program should print out the miles per gallon achieved on each leg and the total mpg for the trip modify the previous program to get its input from file heating and cooling degree-days are measures used by utility companies to estimate energy requirements if the average temperature for day is below then the number of degrees below is added to the heating degree-days if the temperature is above the amount over is added to the cooling degree-days write program that accepts sequence of average daily temps and computes the running total of cooling and heating degree-days the program should print these two totals after all the data has been processed modify the previous program to get its input from file write program that graphically plots regression linethat isthe line with the best fit through collection of points first ask the user to specify the data points by clicking on them in graphics window to find the end of inputplace small rectangle labeled "donein the lower left corner of the windowthe program will stop gathering points when the user clicks inside that rectangle the regression line is the line with the following equationy ( xwhere xi yi nxy mp xi nx is the mean of the -valuesy is the mean of the -valuesand is the number of points as the user clicks on pointsthe program should draw them in the graphics window and keep track of the count of input values and the running sum of xyx and xy values when the user clicks inside the "donerectanglethe program then computes value of (using the equations abovecorresponding to the values at the left and right edges of the window to |
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 understand unit-testing and be able to apply this technique in the implementation and debugging of complex programs simulating racquetball you may not realize itbut you have reached significant milestone in the journey to becoming computer scientist you now have all the tools to write programs that solve interesting problems by interestingi mean problems that would be difficult or impossible to solve without the ability to write and implement computer algorithms you are probably not yet ready to write the next great killer applicationbut you can do some nontrivial computing one particularly powerful technique for solving real-world problems is simulation computers can model real-world processes to provide otherwise unobtainable information computer simulation is used every day to perform myriad tasks such as predicting the weatherdesigning aircraftcreating special effects for moviesand entertaining video game playersto name just few most of these applications require extremely complex programsbut even relatively modest simulations can sometimes shed light on knotty problems in this we are going to develop simple simulation of the game of racquetball along the wayyou will learn some important design and implementation strategies that will help you in tackling your own problems |
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 has led him to question what is going on on the surfaceone would think that players who are slightly better should win slightly more oftenbut against dennythey seem to win the lion' share one obvious possibility is that denny dibblebit' problem is in his head maybe his mental game isn' up to par with his physical skills or perhaps the other players are really much better than he isand he just refuses to see it one daydenny was discussing racquetball with susanwhen she suggested another possibility maybe it is the nature of the game itself that small differences in ability lead to lopsided matches on the court denny was intrigued by the ideahe didn' want to waste money on an expensive sports psychologist if it wasn' going to help but how could he figure out if the problem was mental or just part of the gamesusan suggested she could write computer program to simulate certain aspects of racquetball using the simulationthey could let the computer model thousands of games between players of differing skill levels since there would not be any mental aspects involvedthe simulation would show whether denny is losing more than his share of matches let' write our own racquetball simulation and see what susan and denny discovered analysis and specification racquetball is sport played between two players using racquets to strike ball in four-walled court it has aspects similar to many other ball and racquet games such as tennisvolleyballbadmintonsquashtable tennisetc we don' need to understand all the rules of racquetball to write the programjust the basic outline of the game to start the gameone of the players puts the ball into play--this is called serving the players then alternate hitting the ball to keep it in playthis is rally the rally ends when one of the players fails to hit legal shot the player who misses the shot loses the rally if the loser is the player who servedthen service passes to the other player if the server wins the rallya point is awarded players can only score points during their own service the first player to reach points wins the game in our simulationthe ability-level of the players will be represented by the probability that the player wins the rally when he or she serves thusplayers with probability win point on of their serves the program will prompt the user to enter the service probability for both players and then simulate multiple games of racquetball using those probabilities the program will then print summary of the results here is detailed specificationinput the program first prompts for and gets the service probabilities of the two players (called "player aand "player "then the program prompts for and gets the number of games to be simulated |
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 player here is an examplegames simulated wins for ( %wins for ( %notesall inputs are assumed to be legal numeric valuesno error or validity checking is required in each simulated gameplayer serves first pseudo random numbers our simulation program will have to deal with uncertain events when we say that player wins of the servesthat does not mean that every other serve is winner it' more like coin toss overallwe expect that half the time the coin will come up heads and half the time it will come up tailsbut there is nothing to prevent run of five tails in row similarlyour racquetball player should win or lose rallies randomly the service probability provides likelihood that given serve will be wonbut there is no set pattern many simulations share this property of requiring events to occur with certain likelihood driving simulation must model the unpredictability of other driversa bank simulation has to deal with the random arrival of customers these sorts of simulations are sometimes called monte carlo algorithms because the results depend on "chanceprobabilities of courseyou know that there is nothing random about computersthey are instruction-following machines how can computer programs model seemingly random happeningssimulating randomness is well-studied problem in computer science remember the chaos program from the numbers produced by that program seemed to jump around randomly between zero and one this apparent randomness came from repeatedly applying function to generate sequence of numbers similar approach can be used to generate random (actually pseudo randomnumbers pseudo random number generator works by starting with some seed value this value is fed to function to produce "randomnumber the next time random number is neededthe current value is fed back into the function to produce new number with carefully chosen functionthe resulting sequence of values looks essentially random of courseif you start the process over again with the same seed valueyou end up with exactly the same sequence of numbers it' all determined by the generating function and the value of the seed so probabilistic simulations written in python could be called monte python programs (nudgenudgewink,wink |
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 will also get unique sequence of pseudo random values the two functions of greatest interest to us are randrange and random the randrange function is used to select pseudo random int from given range it can be used with onetwoor three parameters to specify range exactly as with the range function for examplerandrange( , returns some number from the range [ , , , , ]and randrange( , , returns multiple of between and inclusive (rememberranges go up tobut do not includethe stopping value each call to randrange generates new pseudo random int here is an interactive session that shows randrange in actionfrom random import randrange randrange( , randrange( , randrange( , randrange( , randrange( , randrange( , randrange( , randrange( , randrange( , notice it took nine calls to randrange to eventually generate every number in the range - the value came up almost half of the time this shows the probabilistic nature of random numbers over the long haulthis function produces uniform distributionwhich means that all values will appear an (approximatelyequal number of times the random function can be used to generate pseudo random floating point values it takes no parameters and returns values uniformly distributed between and (including but excluding here are some interactive examplesfrom random import random random( |
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 probability is this means that they should win of their serves you can imagine decision in the program something like thisif score score we need to insert probabilistic condition that will succeed of the time suppose we generate random value between and exactly of the interval is to the left of so of the time the random number will be the other of the time (the goes on the upper endbecause the random generator can produce but never in generalif prob represents the probability that the player wins servethe condition random(prob will succeed with just the right probability here is how the decision will lookif random(probscore score top-down design now you have the complete specification for our simulation and the necessary knowledge of random numbers to get the job done go ahead and take few minutes to write up the programi'll wait okseriouslythis is more complicated program than you've probably attempted so far you may not even know where to begin if you're going to make it through with minimal frustrationyou'll need systematic approach one proven technique for tackling complex problems is called top-down design the basic idea is to start with the general problem and try to express solution in terms of smaller problems then each of the smaller problems is attacked in turn using the same technique eventually the problems get so small that they are trivial to solve then you just put all the pieces back together andvoilayou've got program |
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 need to get the simulation inputs from the usersimulate bunch of gamesand print out report here is basic algorithmprint an introduction get the inputsprobaprobbn simulate games of racquetball using proba and probb print report on the wins for playera and playerb now that we've got an algorithmwe're ready to write program know what you're thinkingthis design is too high-levelyou don' have any idea yet how it' all going to work that' ok whatever we don' know how to dowe'll just ignore for now imagine that all of the components you need to implement the algorithm have already been written for you your job is to finish this top-level algorithm using those components first we have to print an introduction think know how to do this it just requires few print statementsbut don' really want to bother with it right now it seems an unimportant part of the algorithm 'll procrastinate and pretend that someone else will do it for me here' the beginning of the programdef main()printintro(do you see how this worksi' just assuming there is printintro function that takes care of printing the instructions that step was easylet' move on nexti need to get some inputs from the user also know how to do that-- just need few input statements againthat doesn' seem very interestingand feel like putting off the details let' assume that component already exists to solve that problem we'll call the function getinputs the point of this function is to get values for variables probaprobband the function must return these values for the main program to use here is our program so fardef main()printintro(probaprobbn getinputs(we're making progresslet' move on to the next line here we've hit the crux of the problem we need to simulate games of racquetball using the values of proba and probb this timei really don' have very good idea how that will even be accomplished let' procrastinate again and push the details off into function (maybe we can get someone else to write that part for us later but what should we put into mainlet' call our function simngames we need to figure out what the call of this function looks like suppose you were asking friend to actually carry out simulation of games what information would you have to give himyour friend would need to know how many games he was |
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 many games were won by player these must be outputs from the simngames function remember in the discussion of functions in said that parameters were used as function inputsand return values serve as function outputs given this analysiswe now know how the next step of the algorithm can be coded def main()printintro(probaprobbn getinputs(winsawinsb simngames(nprobaprobbare you getting the hang of thisthe last step is to print report if you told your friend to type up the reportyou would have to tell him how many wins there were for each playerthese values are inputs to the function here' the complete programdef main()printintro(probaprobbn getinputs(winsawinsb simngames(nprobaprobbprintsummary(winsawinsbthat wasn' very hard the main function is only five lines longand the program looks like more precise formulation of the rough algorithm separation of concerns of coursethe main function alone won' do very muchwe've put off all of the interesting details in factyou may think that we have not yet accomplished anything at allbut that is far from true we have broken the original problem into four independent tasksprintintrogetinputssimngames and printsummary furtherwe have specified the nameparametersand expected return values of the functions that perform these tasks this information is called the interface or signature of function having signatures allows us to tackle pieces independently for the purposes of mainwe don' care how simngames does its job the only concern is thatwhen given the number of games to simulate and the two probabilitiesit must hand back the correct number of wins for each player the main function only cares what each (sub-)function does our work so far can be represented as structure chart (also called module hierarchy chartfigure illustrates this each component in the design is rectangle line connecting two rectangles indicates that the one above uses the one below the arrows and annotations show the interfaces between the components in terms of information flow at each level of designthe interface tells us which details of the lower level are important anything else can be ignored (for the momentthe general process of determining the important |
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 top-down design as systematic method for discovering useful abstractions second-level design now all we need to do is repeat the design process for each of the remaining components let' take them in order the printintro function should print an introduction to the program let' compose suitable sequence of print statements def 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 player always"print("has the first serve "notice the second line wanted to put double quotes around "aand "bso that the entire string is enclosed in apostrophes this function comprises only primitive python instructions since we didn' introduce any new functionsthere is no change to our structure chart now let' tackle getinputs we need to prompt for and get three valueswhich are returned to the main program againthis is simple to code def getinputs()returns the three simulation parameters probaprobb and eval(input("what is the prob player wins serve") eval(input("what is the prob player wins serve") eval(input("how many games to simulate")return abn notice that have taken some shortcuts with the variable names remembervariables inside of function are local to that function this function is so shortit' very easy to see what the three |
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 problemsimngames this one requires bit more thought the basic idea is to simulate games and keep track of how many wins there are for each player well"simulate gamessounds like counted loopand tracking wins sounds like the job for couple of accumulators using our familiar patternswe can piece together an algorithm initialize winsa and winsb to loop times simulate game if playera wins add one to winsa else add one to winsb it' pretty rough designbut then so was our top-level algorithm we'll fill in the details by turning it into python code rememberwe already have the signature for our function def simngames(nprobaprobb)simulates games and returns winsa and winsb we'll add to this by initializing the two accumulator variables and adding the counted loop heading def simngames(nprobaprobb)simulates games and returns winsa and winsb winsa winsb for in range( )the next step in the algorithm calls for simulating game of racquetball ' not quite sure how to do thatso as usuali'll put off the details let' just assume there' function called simonegame to take care of this we need to figure out what the interface for this function will be the inputs for the function seem straightforward in order to accurately simulate gamewe need to know what the probabilities are for each player but what should the output bein the next step of the algorithmwe will need to know who won the game how do you know who wongenerallyyou look at the final score let' have simonegame return the final scores for the two players we can update our structure chart to reflect these decisions the result is shown in figure translating this structure into code yields this nearly completed function |
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 finallywe need to check the scores to see who won and update the appropriate accumulator here is the resultdef simngames(nprobaprobb)winsa winsb for in range( )scoreascoreb simonegame(probaprobbif scorea scorebwinsa winsa elsewinsb winsb return winsawinsb third-level design everything seems to be coming together nicely let' keep working on the guts of the simulation the next obvious point of attack is simonegame here' where we actually have to code up the logic of the racquetball rules players keep doing rallies until the game is over that suggests some kind |
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 accumulatorsbut how do we keep track of who' servingit' either player or player one approach is to use string variable that stores either "aor "bit' also an accumulator of sortsbut to update its value we just switch it from one value to the other that' enough analysis to put together rough algorithm let' try thisinitialize scores to set serving to "aloop while game is not oversimulate one serve of whichever player is serving update the status of the game return scores it' startat least clearly there' still some work to be done on this one we can quickly fill in the first couple of steps of the algorithm to get the following def simonegame(probaprobb)scorea scoreb serving "awhile the question at this point is exactly what the condition will be we need to keep looping as long as the game is not over we should be able to tell if the game is over by looking at the scores we discussed number of possibilities for this condition in the previous some of which were fairly complex let' hide the details in another functiongameoverthat looks at the scores and returns true if the game is overand false if it is not that gets us on to the rest of the loop for now figure shows the structure chart with our new function the code for simonegame now looks like thisdef simonegame(probaprobb)scorea scoreb serving "awhile not gameover(scoreascoreb)inside the loopwe need to do single serve rememberwe are going to compare random number to probability in order to determine if the server wins the point (random(probthe correct probability to use is determined by the value of serving we will need decision based on this value if is servingthen we need to use ' probabilityandbased on the result of the serveupdate either ' score or change the service to here is the code |
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 courseif is not servingwe need to do the same thingonly for we just need to attach mirror image else clause if serving =" "if random(probascorea scorea elseserving "belseif random(probbscoreb scoreb elseserving "aa wins the serve loses serve wins the serve loses the serve that pretty much completes the function it got bit complicatedbut seems to reflect the rules |
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 just one more troublesome function leftgameover here is what we know about it so fardef gameover( , ) and represent scores for racquetball game returns true if the game is overfalse otherwise according to the rules for our simulationa game is over when either player reaches total of we can check this with simple boolean condition def gameover( , ) and represent scores for racquetball game returns true if the game is overfalse otherwise return == or == notice how this function directly computes and returns the boolean result all in one step we've done itexcept for printsummarythe program is complete let' fill in the missing details and call it wrap here is the complete program from start to finishrball py from random import random def main()printintro( |
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 player always"print("has the first serve "def getinputs()returns the three simulation parameters eval(input("what is the prob player wins serve") eval(input("what is the prob player wins serve") eval(input("how many games to simulate")return abn def simngames(nprobaprobb)simulates games of racquetball between players whose abilities are represented by the probability of winning serve returns number of wins for and winsa winsb for in range( )scoreascoreb simonegame(probaprobbif scorea scorebwinsa winsa elsewinsb winsb return winsawinsb def simonegame(probaprobb)simulates single game or racquetball between players whose abilities are represented by the probability of winning serve returns final scores for and serving "ascorea scoreb while not gameover(scoreascoreb)if serving =" "if random(probascorea scorea |
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("wins for { ({ : %})format(winsawinsa/ )print("wins for { ({ : %})format(winsbwinsb/ )if __name__ ='__main__'main(you might take notice of the string formatting in printsummary the type specifier is useful for printing percentages python automatically multiplies the number by and adds trailing percent sign summary of the design process you have just seen an example of top-down design in action now you can really see why it' called top-down design we started at the highest level of our structure chart and worked our way down at each levelwe began with general algorithm and then gradually refined it into precise code this approach is sometimes called step-wise refinement the whole process can be summarized in four steps express the algorithm as series of smaller problems develop an interface for each of the small problems detail the algorithm by expressing it in terms of its interfaces with the smaller problems repeat the process for each smaller problem top-down design is an invaluable tool for developing complex algorithms the process may seem easysince 've walked you through it step by step when you first try it out for yourself |
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 expressing your own programs in terms of cooperating functions will become second nature bottom-up implementation now that we've got program in handyour inclination might be to run offtype the whole thing inand give it try if you do thatthe result will probably be disappointment and frustration even though we have been very careful in our designthere is no guarantee that we haven' introduced some silly errors even if the code is flawlessyou'll probably make some mistakes when you enter it just as designing program one piece at time is easier than trying to tackle the whole problem at onceimplementation is best approached in small doses unit testing good way to approach the implementation of modest size program is to start at the lowest levels of the structure chart and work your way uptesting each component as you complete it looking back at the structure chart for our simulationwe could start with the gameover function once this function is typed into module filewe can immediately import the file and test it here is sample session testing out just this functionimport rball rball gameover( , false rball gameover( , false rball gameover( , true rball gameover( , true have selected test data that tries all the important cases for the function the first time it is calledthe score will be to the function correctly responds with falsethe game is not over as the game progressesthe function will be called with intermediate scores the second example shows that the function again responded that the game is still in progress the last two examples show that the function correctly identifies that the game is over when either player reaches having confidence that gameover is functioning correctlynow we can go back and implement the simonegame function this function has some probabilistic behaviorso ' not sure exactly what the output will be the best we can do in testing it is to see that it behaves reasonably here is sample session |
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 rout that squares with how we think this function should behave we can continue this piecewise implementationtesting out each component as we add it into the code software engineers call this process unit testing testing each function independently makes it easier to spot errors by the time you get around to testing the entire programchances are that everything will work smoothly separating concerns through modular design makes it possible to design sophisticated programs separating concerns through unit testing makes it possible to implement and debug sophisticated programs try these techniques for yourselfand you'll see that you are getting your programs working with less overall effort and far less frustration simulation results finallywe can take look at denny dibblebit' question is it the nature of racquetball that small differences in ability lead to large differences in the outcomesuppose denny wins about of his serves and his opponent is better how often should denny win the gamehere' an example run where denny' opponent always serves first this program simulates game of racquetball between two players called "aand "bthe abilities of each player is indicated by probability ( number between and that |
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 three games his chances of winning threeor five-game match are pretty slim apparentlydenny is winning his share he should skip the shrink and work harder on his game speaking of matchesexpanding this program to compute the probability of winning multi-game matches would be great exercise why don' you give it try other design techniques top-down design is very powerful technique for program designbut it is not the only way to go about creating program sometimes you may get stuck at step and not know how to go about refining it or the original specification might be so complicated that refining it level-by-level is just too daunting prototyping and spiral development another approach to design is to start with simple version of program or program component and then try to gradually add features until it meets the full specification the initial stripped-down version is called prototype prototyping often leads to sort of spiral development process rather than taking the entire problem and proceeding through specificationdesignimplementationand testingwe first designimplementand test prototype then new features are designedimplementedand tested we make many mini-cycles through the development process as the prototype is incrementally expanded into the final program as an exampleconsider how we might have approached the racquetball simulation the very essence of the problem is simulating game of racquetball we might have started with just the simonegame function simplifying even furtherour prototype could assume that each player has - chance of winning any given point and just play series of rallies that leaves the crux of the problemwhich is handling the awarding of points and change of service here is an example prototypefrom random import random def simonegame() |
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 the prototype is playing game here is some example output it' not prettybut it shows that we have gotten the scoring and change of service working we could then work on augmenting the program in phases here' project planphase initial prototype play rallies where the server always has chance of winning print out the scores after each serve phase add two parameters to represent different probabilities for the two players phase play the game until one of the players reaches points at this pointwe have working simulation of single game phase expand to play multiple games the output is the count of games won by each player phase build the complete program add interactive inputs and nicely formatted report of the results |
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 be working for youtry some spiral development the art of design it is important to note that spiral development is not an alternative to top-down design ratherthey are complementary approaches when designing the prototypeyou will still use top-down techniques in you will see yet another approach called object-oriented design there is no "one true wayof design the truth is that good design is as much creative process as science designs can be meticulously analyzed after the factbut there are no hard and fast rules for producing design the best software designers seem to employ variety of techniques you can learn about techniques by reading books like this onebut books can' teach how and when to apply them that you have to learn for yourself through experience in designas in almost anythingthe key to success is practice summary computer simulation is powerful technique for answering questions about real-world processes simulation techniques that rely on probabilistic or chance events are known as monte carlo simulations computers use pseudo random numbers to perform monte carlo simulations top-down design is technique for designing complex programs the basic steps are express an algorithm in terms of smaller problems develop an interface for each of the smaller problems express the algorithm in terms of its interfaces with the smaller problems repeat the process for each of the smaller problems top-down design was illustrated by the development of program to simulate the game of racquetball unit-testing is the process of trying out each component of larger program independently unit-testing and bottom-up implementation are useful in coding complex programs spiral development is the process of first creating simple version (prototypeof complex program and gradually adding more features prototyping and spiral development are often useful in conjunction with top-down design design is combination of art and science practice is the best way to become better designer |
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 functional structure chart top-down design is best implemented from the top down unit-testing is the process of trying out component of larger program in isolation developer should use either top-down or spiral designbut not both read design books alone will make you great designer simplified version of program is called simulation multiple choice which expression is true approximately of the timearandom(> crandom( brandom( drandom(> which of the following is not step in pure top-down designarepeat the process on smaller problems bdetail the algorithm in terms of its interfaces with smaller problems cconstruct simplified prototype of the system dexpress the algorithm in terms of smaller problems graphical view of the dependencies among components of design is called (naflowchart bprototype cinterface dstructure chart the arrows in module hierarchy chart depict ainformation flow bcontrol flow csticky-note attachment done-way streets in top-down designthe subcomponents of the design are aobjects bloops cfunctions dprograms simulation that uses probabilistic events is called amonte carlo bpseudo random cmonty python dchaotic |
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 structure to start unit-testing is athe top bthe bottom cthe middle dthe main function discussion draw the top levels of structure chart for program having the following main functiondef main()printintro(lengthwidth getdimensions(amtneeded computeamount(length,widthprintreport(lengthwidthamtneeded write an expression using either random or randrange to calculate the followinga random int in the range - random float in the range random number representing the roll of six-sided die random number representing the sum resulting from rolling two six-sided dice random float in the range in your own wordsdescribe what factors might lead designer to choose spiral development over top-down approach programming exercises revise the racquetball simulation so that it computes the results for best of game matches first service alternatesso player serves first in the odd games of the matchand player serves first in the even games revise the racquetball simulation to take shutouts into account your updated version should report for both players the number of winspercentage of winsnumber of shutoutsand percentage of wins that are shutouts |
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 awarded pointeven if they were not the serving team games are played to score of design and implement simulation of volleyball using rally scoring design and implement system that compares regular volleyball games to those using rally scoring your program should be able to investigate whether rally scoring magnifiesreducesor has no effect on the relative advantage enjoyed by the better team design and implement simulation of some other racquet sport ( tennis or table tennis craps is dice game played at many casinos player rolls pair of normal six-sided dice if the initial roll is or the player loses if the roll is or the player wins any other initial roll causes the player to "roll for point that isthe player keeps rolling the dice until either rolling or re-rolling the value of the initial roll if the player re-rolls the initial value before rolling it' win rolling first is loss write program to simulate multiple games of craps and estimate the probability that the player wins for exampleif the player wins out of gamesthen the estimated probability of winning is / blackjack (twenty-oneis casino game played with cards the goal of the game is to draw cards that total as close to points as possible without going over all face cards count as pointsaces count as or and all other cards count their numeric value the game is played against dealer the player tries to get closer to (without going overthan the dealer if the dealer busts (goes over )the player automatically wins (provided the player had not already bustedthe dealer must always take cards according to fixed set of rules the dealer takes cards until he or she achieves total of at least if the dealer' hand contains an aceit will be counted as when that results in total between and inclusiveotherwisethe ace is counted as write program that simulates multiple games of blackjack and estimates the probability that the dealer will bust hintstreat the deck of cards as infinite (casinos use "shoecontaining many decksyou do not need to keep track of the cards in the handjust the total so far (treating an ace as and bool variable hasace that tells whether or not the hand contains an ace hand containing an ace should have points added to the total exactly when doing so would produce stopping total (something between and inclusive blackjack dealer always starts with one card showing it would be useful for player to know the dealer' bust probability (see previous problemfor each possible starting value write simulation program that runs multiple hands of blackjack for each possible starting value (ace- and estimates the probability that the dealer busts for each starting value |
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 dart board and the cabinet if is the total number of darts randomly thrown (that land within the confines of the cabinet)and is the number that hit the boardit is easy to show that write program that accepts the "number of dartsas an input and then performs simulation to estimate hintyou can use *random( to generate the and coordinates of random point inside square centered at ( the point lies inside the inscribed circle if < write program that performs simulation to estimate the probability of rolling five-of- -kind in single roll of five six-sided dice random walk is particular kind of probabilistic simulation that models certain statistical systems such as the brownian motion of molecules you can think of one-dimensional random walk in terms of coin flipping suppose you are standing on very long straight sidewalk that extends both in front of and behind you you flip coin if it comes up headsyou take step forwardtails means to take step backward suppose you take random walk of steps on averagehow many steps away from the starting point will you end upwrite program to help you investigate this question suppose you are doing random walk (see previous problemon the blocks of city street at each "stepyou choose to walk one block (at randomeither forwardbackwardleft or right in stepshow far do you expect to be from your starting pointwrite program to help answer this question write graphical program to trace random walk (see previous two problemsin two dimensions in this simulation you should allow the step to be taken in any direction you can generate random direction as an angle off of the axis angle random( math pi the new and positions are then given by these formulasx cos(angley sin(anglethe program should take the number of steps as an input start your walker at the center of grid and draw line that traces the walk as it progresses |
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 one of the walls so that you are now half-way between it and the center of the cube what fraction of your field of vision is now taken up by the closest wallhintuse monte carlo simulation that repeatedly "looksin random direction and counts how many times it sees the wall |
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 class definitions to be able to write interactive graphics programs involving novel (programmer designedwidgets quick review of objects in the last three we have developed techniques for structuring the computations of program in the next few we will take look at techniques for structuring the data that our programs use you already know that objects are one important tool for managing complex data so farour programs have made use of objects created from pre-defined classes such as circle in this you will learn how to write your own classes so that you can create novel objects remember back in defined an object as an active data type that knows stuff and can do stuff more preciselyan object consists of collection of related information set of operations to manipulate that information the information is stored inside the object in instance variables the operationscalled methodsare functions that "liveinside the object collectivelythe instance variables and methods are called the attributes of an object |
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 decide which pixels in window should be colored the move method will change the value of center to reflect the new position of the circle recall that every object is said to be an instance of some class the class of the object determines what attributes the object will have basically class is description of what its instances will know and do new objects are created from class by invoking constructor you can think of the class itself as sort of factory for stamping out new instances consider making new circle objectmycircle circle(point( , ) circlethe name of the classis used to invoke the constructor this statement creates new circle instance and stores reference to it in the variable mycircle the parameters to the constructor are used to initialize some of the instance variables (namely center and radiusinside of mycircle once the instance has been createdit is manipulated by calling on its methodsmycircle draw(winmycircle move(dxdy example programcannonball before launching into detailed discussion of how to write your own classeslet' take short detour to see how useful new classes can be program specification suppose we want to write program that simulates the flight of cannonball (or any other projectile such as bulletbaseballor shot putwe are particularly interested in finding out how far the cannonball will travel when fired at various launch angles and initial velocities the input to the program will be the launch angle (in degrees)the initial velocity (in meters per second)and the initial height (in metersof the cannonball the output will be the distance that the projectile travels before striking the ground (in metersif we ignore the effects of wind resistance and assume that the cannonball stays close to earth' surface ( we're not trying to put it into orbit)this is relatively simple classical physics problem the acceleration of gravity near the earth' surface is about meters per secondper second that means if an object is thrown upward at speed of meters per secondafter one second has passedits upward speed will have slowed to meters per second after another secondthe speed will be only meters per secondand shortly thereafter it will start coming back down |
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 startedalong with the obvious relationship that the distance an object travels in given amount of time is equal to its rate times the amount of time ( rt)we can solve this problem algorithmically designing the program let' start by designing an algorithm for this problem given the problem statementit' clear that we need to consider the flight of the cannonball in two dimensionsheightso we know when it hits the groundand distanceto keep track of how far it goes we can think of the position of the cannonball as point (xyin graph where the value of gives the height above the ground and the value of gives the distance from the starting point our simulation will have to update the position of the cannonball to account for its flight suppose the ball starts at position ( )and we want to check its positionsayevery tenth of second in that intervalit will have moved some distance upward (positive yand some distance forward (positive xthe exact distance in each dimension is determined by its velocity in that direction separating out the and components of the velocity makes the problem easier since we are ignoring wind resistancethe velocity remains constant for the entire flight howeverthe velocity changes over time due to the influence of gravity in factthe velocity will start out being positive and then become negative as the cannonball starts back down given this analysisit' pretty clear what our simulation will have to do here is rough outlineinput the simulation parametersanglevelocityheightinterval calculate the initial position of the cannonballxposypos calculate the initial velocities of the cannonballxvelyvel while the cannonball is still flyingupdate the values of xposyposand yvel for interval seconds further into the flight output the distance traveled as xpos let' turn this into program using stepwise refinement the first line of the algorithm is straightforward we just need an appropriate sequence of input statements here' startdef main()angle eval(input("enter the launch angle (in degrees)")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") |
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 consider the initial velocity as consisting of some amount of change in and some amount of change in xthen these three components (velocityx-velocity and -velocityform right triangle figure illustrates the situation if we know the magnitude of the velocity and the launch angle (labeled thetabecause the greek letter th is often used as the measure of angles)we can easily calculate the magnitude of xvel by the equation xvel velocity cos theta similar formula (using sin thetaprovides yvel ty oci theta yvel velocity sin(thetaxvel velocity cos(thetafigure finding the and components of velocity even if you don' completely understand the trigonometrythe important thing is that we can translate these formulas into python code there' still one subtle issue to consider our input angle is in degreesand the python math library uses radian measures we'll have to convert our angle before applying the formulas there are radians in circle ( degrees)so theta *angle this is such common conversion that the math library provides convenient function called radians that does this computation these three formulas give us the code for computing the initial velocitiestheta math radians(anglexvel velocity math cos(thetayvel velocity math sin(thetathat brings us to the main loop in our program we want to keep updating the position and velocity of the cannonball until it reaches the ground we can do this by examining the value of ypos while ypos > used >as the relationship so that we can start with the cannonball on the ground ( and still get the loop going the loop will quit as soon as the value of ypos dips just below indicating the cannonball has embedded itself slightly in the ground |
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 the cannonball will remain constant and is given by the value of xvel as concrete examplesuppose the ball is traveling at meters per second and is currently meters from the firing point in another secondit will go more meters and be meters from the firing point if the interval is only second (rather than full second)then the cannonball will only fly another ( meters and be at distance of meters you can see that the distance traveled is always given by time xvel to update the horizontal positionwe need just one statementxpos xpos time xvel the situation for the vertical component is slightly more complicatedsince gravity causes the -velocity to change over time each secondyvel must decrease by meters per secondthe acceleration of gravity in seconds the velocity will decrease by ( meters per second the new velocity at the end of the interval is calculated as yvel yvel time to calculate how far the cannonball travels during this intervalwe need to know its average vertical velocity since the acceleration due to gravity is constantthe average velocity will just be the average of the starting and ending velocities(yvel+yvel )/ multiplying this average velocity by the amount of time in the interval gives us the change in height here is the completed loopwhile yvel > xpos xpos time xvel yvel yvel time ypos ypos time (yvel yvel )/ yvel yvel notice how the velocity at the end of the time interval is first stored in the temporary variable yvel this is done to preserve the initial yvel so that the average velocity can be computed from the two values finallythe value of yvel is assigned its new value at the end of the loop this represents the correct vertical velocity of the cannonball at the end of the interval the last step of our program simply outputs the distance traveled adding this step gives us the complete program cball py from math import pisincosradians def main()angle eval(input("enter the launch angle (in degrees)") |
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 vel sin(thetaloop until the ball hits the ground while ypos > calculate position and velocity in time seconds xpos xpos time xvel yvel yvel time ypos ypos time (yvel yvel )/ yvel yvel print("\ndistance traveled{ : fmeters format(xpos)modularizing the program you may have noticed during the design discussion that employed stepwise refinement (top-down designto develop the programbut did not divide the program into separate functions we are going to modularize the program in two different ways firstwe'll use functions ( la top-down designwhile the final program is not too longit is fairly complex for its length one cause of the complexity is that it uses ten variablesand that is lot for the reader to keep track of let' try dividing the program into functional pieces to see if that helps here' version of the main algorithm using helper functionsdef main()anglevelh time getinputs(xposypos xvelyvel getxycomponents(velanglewhile ypos > xposyposyvel updatecannonball(timexposyposxvelyvelprint("\ndistance traveled{ : fmeters format(xpos)it should be obvious what each of these functions does based on their names and the original program code you might take couple of minutes to code the three helper functions |
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 updatecannonball being able to hide some of the intermediate variables is major benefit of the separation of concerns provided by top-down design even this version seems overly complicated look especially at the loop keeping track of the state of the cannonball requires four pieces of informationthree of which must change from moment to moment all four variables along with the value of time are needed to compute the new values of the three that change that results in an ugly function call having five parameters and three return values an explosion of parameters is often an indication that there might be better way to organize program let' try another approach the original problem specification itself suggests better way to look at the variables in our program there is single real-world cannonball objectbut describing it in the current program requires four pieces of informationxposyposxveland yvel suppose we had projectile class that "understoodthe physics of objects like cannonballs using such classwe could express the main algorithm in terms of creating and updating suitable object using single variable with this object-based approachwe might write main like thisdef main()anglevelh time getinputs(cball projectile(anglevelh while cball gety(> cball update(timeprint("\ndistance traveled% meters (cball getx())obviouslythis is much simpler and more direct expression of the algorithm the initial values of angleveland are used as parameters to create projectile called cball each time through the loopcball is asked to update its state to account for time we can get the position of cball at any moment by using its getx and gety methods to make this workwe just need to define suitable projectile class that implements the methods updategetxand gety defining new classes before designing projectile classlet' take an even simpler example to examine the basic ideas examplemulti-sided dice you know that normal die (the singular of diceis cubeand each face shows number from one to six some games employ nonstandard dice that may have fewer ( fouror more ( thirteensides let' design general class msdie to model multi-sided dice we could use such an object in any number of simulation or game programs each msdie object will know two things |
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 current value is here is an interactive example showing what our class will dodie msdie( die getvalue( die roll(die getvalue( die msdie( die getvalue( die roll(die getvalue( die setvalue( die getvalue( do you see how this might be usefuli can define any number of dice having arbitrary numbers of sides each die can be rolled independently and will always produce random value in the proper range determined by the number of sides using our object-oriented terminologywe create die by invoking the msdie constructor and providing the number of sides as parameter our die object will keep track of this number internally using an instance variable another instance variable will be used to store the current value of the die initiallythe value of the die will be set to be since that is legal value for any die the value can be changed by the roll and setroll methods and returned from the getvalue method writing definition for the msdie class is really quite simple class is collection of methodsand methods are just functions here is the class definition for msdiemsdie py class definition for an -sided die from random import randrange class msdie |
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 class makes it method of that classrather than stand-alone function let' take look at the three methods defined in this class you'll notice that each method has first parameter named self the first parameter of method is special--it always contains reference to the object on which the method is acting as usualyou can use any name you want for this parameterbut the traditional name is selfso that is what will always use an example might be helpful in making sense of self suppose we have main function that executes die setvalue( method invocation is function call just as in normal function callspython executes four-step sequence the calling program (mainsuspends at the point of the method application python locates the appropriate method definition inside the class of the object to which the method is being applied in this casecontrol is transferring to the setvalue method in the msdie classsince die is an instance of msdie the formal parameters of the method get assigned the values supplied by the actual parameters of the call in the case of method callthe first formal parameter corresponds to the object in our exampleit is as if the following assignments are done before executing the method bodyself die value the body of the method is executed control returns to the point just after where the method was calledin this casethe statement immediately following die setvalue( |
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 do this implicitlypython requires us to add the extra parameter to avoid confusioni will always refer to the first formal parameter of method as the self parameter and any others as normal parameters soi would say setvalue uses one normal parameter class msdiedef main()die msdie( self=die value= def setvalue(self,value)die setvalue( self value value print die getvalue(figure flow of control in calldie setvalue( okso self is parameter that represents an object but what exactly can we do with itthe main thing to remember is that objects contain their own data conceptuallyinstance variables provide way to remember data inside an object just as with regular variablesinstance variables are accessed by name we can use our familiar dot notationlook at the definition of setvalueself value refers to the instance variable value that is associated with the object each instance of class has its own instance variablesso each msdie object has its very own value certain methods in class have special meaning to python these methods have names that begin and end with two underscores the special method __init__ is the object constructor python calls this method to initialize new msdie the role of __init__ is to provide initial values for the instance variables of an object from outside the classthe constructor is referred to by the class name die msdie( when executing this statementpython creates new msdie and executes __init__ on that object the net result is that die sides is set to and die value is set to the power of instance variables is that we can use them to remember the state of particular objectand this information then gets passed around the program as part of the object the values of instance variables can be referred to again in other methods or even in successive calls to the same method this is different from regular local function variableswhose values disappear once the function terminates here is simple illustrationdie die( print die getvalue( die setvalue( |
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 the object is asked for its value the next timeit responds with that' just about all there is to know about defining new classes in python now it' time to put this new knowledge to use examplethe projectile class returning to the cannonball examplewe want class that can represent projectiles this class will need constructor to initialize instance variablesan update method to change the state of the projectileand getx and gety methods so that we can find the current position let' start with the constructor in the main programwe will create cannonball from the initial anglevelocity and height cball projectile(anglevelh the projectile class must have an __init__ method that uses these values to initialize the instance variables of cball but what should the instance variables beof coursethey will be the four pieces of information that characterize the flight of the cannonballxposyposxveland yvel we will calculate these values using the same formulas that were in the original program here is how our class looks with the constructorclass projectiledef __init__(selfanglevelocityheight)self xpos self ypos height theta math radians(angleself xvel velocity math cos(thetaself yvel velocity math sin(thetanotice how we have created four instance variables inside the object using the self dot notation the value of theta is not needed after __init__ terminatesso it is just normal (localfunction variable the methods for accessing the position of our projectiles are straightforwardthe current position is given by the instance variables xpos and ypos we just need couple of methods that return these values def getx(self)return self xpos |
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 time self ypos self ypos time (self yvel yvel )/ self yvel yvel basicallythis is the same code that we used in the original program updated to use and modify instance variables notice the use of yvel as temporary (ordinaryvariable this new value is saved by storing it into the object in the last line of the method that completes our projectile class we now have complete object-based solution to the cannonball problem cball py from math import pisincosradians class projectiledef __init__(selfanglevelocityheight)self xpos self ypos height theta radians(angleself xvel velocity cos(thetaself yvel velocity sin(thetadef update(selftime)self xpos self xpos time self xvel yvel self yvel time self ypos self ypos time (self yvel yvel self yvel yvel def gety(self)return self ypos def getx(self)return self xpos def getinputs() |
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(> cball update(timeprint("\ndistance traveled{ : fmeters format(cball xpos) data processing with class the projectile example shows how useful class can be for modeling real-world object that has complex behavior another common use for objects is simply to group together set of information that describes person or thing for examplea company needs to keep track of information about all of its employees their personnel system might make use of an employee object that contains data such as the employee' namesocial security numberaddresssalarydepartmentetc grouping of information of this sort is often called record let' try our hand at some simple data processing involving university students in typical universitycourses are measured in terms of credit hoursand grade point averages are calculated on point scale where an "ais pointsa "bis pointsetc grade point averages are generally computed using quality points if class is worth credit hours and the student gets an " ,then he or she earns ( quality points to calculate student' grade point average (gpa)we divide the total quality points by the number of credit hours completed suppose we have data file that contains student grade information each line of the file consists of student' namecredit-hoursand quality points these three values are separated by tab character for examplethe contents of the file might look something like thisadamshenry computewellsusan dibblebitdenny jonesjim smithfrank our job is to write program that reads through this file to find the student with the best gpa and print out his/her namecredits-hoursand gpa we can begin by creating student class an object of type student will be record of information for single student in this casewe have three pieces of informationnamecredit-hoursand quality points we can save this information as instance variables that are initialized in the constructor |
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 hours and qpoints this makes the constructor bit more versatile by allowing it to accept parameters that may be floatsintsor even strings now that we have constructorit' easy to create student records for examplewe can make record for henry adams like this astudent student("adamshenry" using objects allows us to collect all of the information about an individual in single variable next we must decide what methods student object should have obviouslywe would like to be able to access the student' informationso we should define set of accessor methods def getname(self)return self name def gethours(self)return self hours def getqpoints(self)return self qpoints these methods allow us to get information back out of student record for exampleto print student' name we could writeprint(astudent getname()one method that we have not yet included in our class is way of computing gpa we could compute it separately using the gethours and getqpoints methodsbut gpa is so handy that it probably warrants its own method def gpa(self)return self qpoints/self hours with this class in handwe are ready to attack the problem of finding the best student our algorithm will be similar to the one used for finding the max of numbers we'll look through the file of students one by one keeping track of the best student seen so far here' the algorithm for our program |
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 name name self hours float(hoursself qpoints float(qpointsdef getname(self)return self name def gethours(self)return self hours def getqpoints(self)return self qpoints def gpa(self)return self qpoints/self hours def makestudent(infostr)infostr is tab-separated linename hours qpoints returns corresponding student object namehoursqpoints infostr split("\ "return student(namehoursqpointsdef main()open the input file for reading filename input("enter name the grade file"infile open(filename' ' |
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("the best student is:"best getname()print("hours:"best gethours()print("gpa:"best gpa()if __name__ ='__main__'main(you will notice that added helper function called makestudent this function takes single line of the filesplits it into its three tab-separated fieldsand returns corresponding student object right before the loopthis function is used to create record for the first student in the filebest makestudent(infile readline()it is called again inside the loop to process each subsequent line of the file makestudent(linehere' how it looks running the program on the sample data enter name the grade filestudents dat the best student iscomputewellsusan hours gpa one unresolved issue with this program is that it only reports back single student if there multiple students tied for the best gpaonly the first one found is reported leave it as an interesting design issue for you to modify the program so that it reports all students having the highest gpa |
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 definition this gives us the same kind of separation of concerns that we had using functions in top-down design the main program only has to worry about what objects can donot about how they are implemented computer scientists call this separation of concerns encapsulation the implementation details of an object are encapsulated in the class definitionwhich insulates the rest of the program from having to deal with them this is another application of abstraction (ignoring irrelevant details)which is the essence of good design for completenessi should mention that encapsulation is only programming convention in python it is not enforced by the languageper se in our projectile class we included two short methodsgetx and getythat simply returned the values of instance variables xpos and yposrespectively our student class has similar accessor methods for its instance variables strictly speakingthese methods are not absolutely necessary in pythonyou can access the instance variables of any object with the regular dot notation for examplewe could test the constructor for the projectile class interactively by creating an object and then directly inspecting the values of the instance variables projectile( xpos ypos xvel yvel accessing the instance variables of an object is very handy for testing purposesbut it is generally considered poor practice to do this in programs one of the main reasons for using objects is to hide the internal complexities of those objects from the programs that use them references to instance variables should generally remain inside the class definition with the rest of the implementation details from outside the classall interaction with an object should generally be done using the interface provided by its methods howeverthis is not hard and fast ruleand python program designers often specify that certain instance variables are accessible as part of the interface one immediate advantage of encapsulation is that it allows us to modify and improve classes independentlywithout worrying about "breakingother parts of the program as long as the interface provided by class stays the samethe rest of the program can' even tell that class has changed as you begin to design classes of your ownyou should strive to provide each with complete set of methods to make it useful |
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 add documentation that describes how the class can be used so that programmers who want to use the module don' have to study the code to figure out (or rememberwhat the class and its methods do module documentation you are already familiar with one way of documenting programsnamely comments it' always good idea to provide comments explaining the contents of module and its uses in factcomments of this sort are so important that python incorporates special kind of commenting convention called docstring you can insert plain string literal as the first line of moduleclass or function to document that component the advantage of docstrings is thatwhile ordinary comments are simply ignored by pythondocstrings are actually carried along during execution in special attribute called __doc__ these strings can be examined dynamically most of the python library modules have extensive docstrings that you can use to get help on using the module or its contents for exampleif you can' remember how to use the random functionyou can print its docstring directly like thisimport random print(random random __doc__random(- in the interval [ docstrings are also used by the python online help system and by utility called pydoc that automatically builds documentation for python modules you could get the same information using interactive help like thisimport random help(random randomhelp on built-in function randomrandomrandom(- in the interval [ if you want to see whole bunch of information about the entire random moduletry typing help(randomhere is version of our projectile class as module file with docstrings includedprojectile py """projectile py provides simple class for modeling the |
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 velocity and height ""self xpos self ypos height theta radians(angleself xvel velocity cos(thetaself yvel velocity sin(thetadef update(selftime)"""update the state of this projectile to move it time seconds farther into its flight""self xpos self xpos time self xvel yvel self yvel time self ypos self ypos time (self yvel yvel self yvel yvel def gety(self)"returns the position (heightof this projectile return self ypos def getx(self)"returns the position (distanceof this projectile return self xpos you might notice that many of the docstrings in this code are enclosed in triple quotes ("""this is third way that python allows string literals to be delimited triple quoting allows us to directly type multi-line strings here is an example of how the docstrings appear when they are printedprint(projectile projectile __doc__simulates the flight of simple projectiles near the earth' surfaceignoring wind resistance tracking is done in two dimensionsheight (yand distance ( |
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 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(> cball update(timeprint("\ndistance traveled{ : fmeters format(cball getx())in this versiondetails of projectile motion are now hidden in the projectile module file if you are testing multi-module python projects interactively ( good thing to do)you need to be aware of subtlety in the python module importing mechanism when python first imports given moduleit creates module object that contains all of the things defined in the module (technicallythis is called namespaceif module imports successfully (it has no syntax errors)subsequent imports do not reload the modulethey just create additional references to the existing module object even if module has been changed (its source file editedre-importing it into an ongoing interactive session will not get you an updated version it is possible to interactively replace module object using the function reload(in the imp module of the standard library (consult the python documentation for detailsbut often this won' give you the results you want that' because reloading module doesn' change the values of any identifiers in the current session that already refer to objects from the old version of the module in factit' pretty easy to create situation where objects from both the old and new version of module are active at the same timewhich is confusing to say the least the simplest way to avoid this confusion is to make sure you start new interactive session for testing each time any of the modules involved in your tests is modified that way you are guaranteed to get fresh (updatedimport of all the modules that you are using |
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 custom widgets example programdice roller let' try our hand at building couple of useful widgets as an example applicationconsider program that rolls pair of standard (six-sideddice the program will display the dice graphically and provide two buttonsone for rolling the dice and one for quitting the program figure shows snapshot of the user interface figure snapshot of dice roller in action you can see that this program has two kinds of widgetsbuttons and dice we can start by developing suitable classes the two buttons will be instances of button classand the class that provides graphical view of the value of die will be dieview building buttons buttonsof courseare standard elements of virtually every gui these days modern buttons are very sophisticatedusually having -dimensional look and feel our simple graphics package does not have the machinery to produce buttons that appear to depress as they are clicked the best we |
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 when they have been clicked in additionit is also nice to be able to activate and deactivate individual buttons that wayour applications can signal which options are available to the user at any given moment typicallyan inactive button is grayed-out to show that it is not available summarizing this descriptionour buttons will support the following methodsconstructor create button in window we will have to specify the window in which the button will be displayedthe location/size of the buttonand the label that will be on the button activate set the state of the button to active deactivate set the state of the button to inactive clicked indicate if the button was clicked if the button is activethis method will determine if the point clicked is inside the button region the point will have to be sent as parameter to the method getlabel returns the label string of the button this is provided so that we can identify particular button in order to support these operationsour buttons will need number of instance variables for examplethe button itself will be drawn as rectangle with some text centered in it invoking the activate and deactivate methods will change the appearance of the button saving the rectangle and text objects as instance variables will allow us to change the width of the outline and the color of the label we might start by implementing the various methods to see what other instance variables might be needed once we have identified the relevant variableswe can write constructor that initializes these values let' start with the activate method we can signal that the button is active by making the outline thicker and making the label text black here is the code (remember the self parameter refers to the button object)def activate(self)"sets this button to 'activeself label setfill('black'self rect setwidth( self active true as mentioned abovein order for this code to workour constructor will have to initialize self label as an appropriate text object and self rect as rectangle object in additionthe self active instance variable stores boolean value to remember whether or not the button is currently active our deactivate method will do the inverse of activate it looks like this |
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 where the mouse was clicked if an application needs to get button clickit will first have to call getmouse and then see which active button (if anythe point is inside of we could imagine the button processing code looking something like the followingpt win getmouse(if button clicked(pt)do button stuff elif button clicked(pt)do button stuff elif button clicked(ptdo button stuff the main job of the clicked method is to determine whether given point is inside the rectangular button the point is inside the rectangle if its and coordinates lie between the extreme and values of the rectangle this would be easiest to figure out if we just assume that the button object has instance variables that record the min and max values of and assuming the existence of instance variables xminxmaxyminand ymaxwe can implement the clicked method with single boolean expression def clicked(selfp)"returns true if button is active and is insidereturn (self active and self xmin < getx(<self xmax and self ymin < gety(<self ymaxhere we have single large boolean expression composed by anding together three simpler expressionsall three must be true for the function to return true value the first of the three subexpressions simply retrieves the value of the instance variable self active this ensures that only active buttons will report that they have been clicked if self active is falsethen clicked will return false the second two subexpressions are compound conditions to check that the and values of the point fall between the edges of the button rectangle (rememberx < < means the same as the mathematical expression < < (section )now that we have the basic operations of the button ironed outwe just need constructor to get all the instance variables properly initialized it' not hardbut it is bit tedious here is the complete class with suitable constructor |
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(mywincenterpointwidthheight'quit'"" , width/ height/ , center getx()center gety(self xmaxself xmin +wx- self ymaxself ymin +hy- point(self xminself yminp point(self xmaxself ymaxself rect rectangle( , self rect setfill('lightgray'self rect draw(winself label text(centerlabelself label draw(winself deactivate(def clicked(selfp)"returns true if button active and is insidereturn (self active and self xmin < getx(<self xmax and self ymin < gety(<self ymaxdef getlabel(self)"returns the label string of this button return self label gettext(def activate(self)"sets this button to 'activeself label setfill('black'self rect setwidth( self active true |
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 instance variables are calculated from these parameters building dice now we'll turn our attention to the dieview class the purpose of this class is to display the value of die in graphical fashion the face of the die will be square (via rectangleand the pips will be circles our dieview will have the following interfaceconstructor create die in window we will have to specify the windowthe center point of the dieand the size of the die as parameters setvalue change the view to show given value the value to display will be passed as parameter obviouslythe heart of dieview is turning various pips "onand "offto indicate the current value of the die one simple approach is to pre-place circles in all the possible locations where pip might be and then turn them on or off by changing their colors using the standard position of pips on diewe will need seven circlesthree down the left edgethree down the right edgeand one in the center the constructor will create the background square and the seven circles the setvalue method will set the colors of the circles based on the value of the die without further adohere is the code for our dieview class the comments will help you to follow how it worksdieview py from graphics import class dieview""dieview is widget that displays graphical representation of standard six-sided die ""def __init__(selfwincentersize)"""create view of diee gdie(mywinpoint( , ) creates die centered at ( , having sides |
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 cxcy center getx()center gety( point(cx-hsizecy-hsizep point(cx+hsizecy+hsizerect rectangle( , rect draw(winrect setfill(self backgroundcreate circles for standard pip locations 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+offsetcyself pip self __makepip(cx+offsetcy+offsetdraw an initial value self setvalue( def __makepip(selfxy)"internal helper method to draw pip at ( , )pip circle(point( , )self psizepip setfill(self backgroundpip setoutline(self backgroundpip draw(self winreturn pip def setvalue(selfvalue)"set this die to display value turn all pips off self pip setfill(self background |
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(self foregroundelif value = self pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundelif value = self pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundelif value = self pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundelseself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundthere are couple of things worth noticing in this code firstin the constructori have defined set of values that determine various aspects of the die such as its color and the size of the pips calculating these values in the constructor and then using them in other places allows us to easily tweak the appearance of the die without having to search through the code to find all the places where those values are used actually figured out the specific calculations (such as the pip size being one-tenth of the die sizethrough process of trial and error another important thing to notice is that have added an extra method __makepip that was |
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 __makepip(cxcymethod names beginning with single or double underscore are used in python to indicate that method is "privateto the class and not intended for use by outside programs the main program now we are ready to write our main program the button and dieview classes are imported from their respective modules here is the program that uses our new widgetsroller py graphics program to roll pair of dice uses custom widgets button and dieview from random import randrange from graphics import graphwinpoint from button import button from dieview import dieview def main()create the application window win graphwin("dice roller"win setcoords( win setbackground("green "draw the interface widgets die dieview(winpoint( , ) die dieview(winpoint( , ) rollbutton button(winpoint( , ) "roll dice"rollbutton activate(quitbutton button(winpoint( , ) "quit"event loop pt win getmouse(while not quitbutton clicked(pt)if rollbutton clicked(pt)value randrange( , die setvalue(value value randrange( , |
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 deactivated the quit button is activated inside the event loop below when the roll button is clicked this approach forces the user to roll the dice at least once before quitting the heart of the program is the event loop it is just sentinel loop that gets mouse clicks and processes them until the user successfully clicks the quit button the if inside the loop ensures that the rolling of the dice only happens when the roll button is clicked clicking point that is not inside either button causes the loop to iteratebut nothing is actually done summary this has shown you how to work with class definitions here is summary of some key pointsan object comprises collection of related data and set of operations to manipulate that data data is stored in instance variables and manipulated via methods every object is an instance of some class it is the class definition that determines what the attributes of the object will be programmers can create new kinds of objects by writing suitable class definitions python class definition is collection of function definitions these functions implement the methods of the class every method definition has special first parameter called self the actual parameter of self is the object to which the method is being applied the self parameter is used to access the attributes of the object via dot notation the special method __init__ is the constructor for class its job is to initialize the instance variables of an object defining new objects (via classcan simplify the structure of program by allowing single variable to store constellation of related data objects are useful for modeling real world entities these entities may have complex behavior that is captured in method algorithms ( projectileor they may be little more than collection of relevant information about some individual ( student record |
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 be accessed or modified through the interface methods of the class most gui systems are built using an object-oriented approach we can build novel gui widgets by defining suitable classes exercises review questions true/false new objects are created by invoking constructor functions that live in objects are called instance variables the first parameter of python method definition is called this an object may have only one instance variable in data processinga collection of information about person or thing is called file in python classthe constructor is called __init__ docstring is the same thing as comment instance variables go away once method terminates method names should always begin with one or two underscores it is considered bad style to directly access an instance variable outside of class definition multiple choice what python reserved word starts class definitionadef bclass cobject d__init__ method definition with four formal parameters is generally called with how many actual parametersathree bfour cfive dit depends method definition is similar to (naloop bmodule cimport statement dfunction definition |
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 definitions is aobscuring bsubclassing cdocumentation dencapsulation python string literal can span multiple lines if enclosed with abc"" in dieview widgetwhat is the data type of the instance variable activeabool bint cfloat dmsdie which of the following methods is not part of the button class in this aactivate bdeactivate csetlabel dclicked which of the following methods is part of the dieview class in this aactivate bsetcolor csetvalue dclicked discussion explain the similarities and differences between instance variables and "regularfunction variables explain the following in terms of actual code that might be found in class definition(amethod (binstance variable (cconstructor (daccessor (emutator show the output that would result from the following nonsense programclass bozodef __init__(selfvalue)print "creating bozo from:"value self value value |
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 discussed in this to build gui for one (or moreof your projects from previous write program to play "three button monte your program should draw three buttons labeled "door ""door ,and "door in window and randomly select one of the buttons (without telling the user which one is selectedthe program then prompts the user to click on one of the buttons click on the special button is winand click on one of the other two is loss you should tell the user whether they won or lostand in the case of losswhich was the correct button your program should be entirely graphicalthat isall prompts and messages should be displayed in the graphics window extend the program from the previous problem by allowing the player to play multiple rounds and displaying the number of wins and losses add "quitbutton for ending the game modify the student class from the by adding mutator method that records grade for the student here is the specification of the new methodaddgrade(selfgradepointcreditsgradepoint is float that represents grade ( etc )and credits is float indicating the number of credit hours for the class modifies the student object by adding this grade information use the updated class to implement simple program for calculating gpa your program should create new student object that has credits and quality points (the name is irrelevantyour program should then prompt the user to enter course information (gradepoint and creditsand then print out the final gpa achieved |
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 your class cbutton and implement the exact same methods that are in the existing button class your constructor should take the center of the button and its radius as normal parameters place your class in module called cbutton py test your class by modifying roller py to use your buttons modify the dieview class from the by adding method that allows the color of the pips to be specified setcolor(selfcolorchanges the color of the pips to color hintsyou can change the color by changing the value of the instance variable foregroundbut you also need to redraw the die after doing this modify setvalue so that it remembers the value of the die in an instance variable then setcolor can call setvalue and pass the stored value to redraw the die you can test your new class with the roller py program have the dice change to random color after each roll (you can generate random color with the color_rgb function write class to represent the geometric solid sphere your class should implement the following methods__init__(selfradiuscreates sphere having the given radius getradius(selfreturns the radius of this sphere surfacearea(selfreturns the surface area of the sphere volume(selfreturns the volume of the sphere use your new class to solve programming exercise from same as the previous problembut for cube the constructor should accept the length of side as parameter implement class to represent playing card your class should have the following methods__init__(selfranksuitrank is an int in the range - indicating the ranks acekingand suit is single character " "" "" "or "sindicating the suit (diamondsclubsheartsor spadescreate the corresponding card getrank(selfreturns the rank of the card getsuit(selfreturns the suit of the card bjvalue(selfreturns the blackjack value of card ace counts as face cards count as __str__(selfreturns string that names the card for example"ace of spades |
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 the user extend your card class from the previous problem with draw(selfwincentermethod that displays the card in graphics window use your extended class to create and display hand of five random cards hintthe easiest way to do this is to search the internet for free set of card images and use the image object in the graphics library to display them here is simple class that draws (grimface in graphics windowface py from graphics import class facedef __init__(selfwindowcentersize)eyesize size eyeoff size mouthsize size mouthoff size self head circle(centersizeself head draw(windowself lefteye circle(centereyesizeself lefteye move(-eyeoff-eyeoffself righteye circle(centereyesizeself righteye move(eyeoff-eyeoffself lefteye draw(windowself righteye draw(windowp center clone( move(-mouthsize/ mouthoffp center clone( move(mouthsize/ mouthoffself mouth line( , self mouth draw(windowadd methods to this class that cause the face to change expression for example you might add methods such as smilewinkfrownflinchetc your class should implement at least three such methods |
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 exercise from bonushave the face change expression each time it "hitsthe edge of the window create tracker class that displays circle in graphics window to show the current location of an object here is quick specification of the classclass trackerdef __init__(selfwindowobjtotrack)window is graphwin and objtotrack is an object whose position is to be shown in the window objtotrack is an object that has getx(and gety(methods that report its current position creates tracker object and draws circle in window at the current position of objtotrack def update()moves the circle in the window to the current position of the object being tracked use your new tracker class in conjunction with the projectile class to write program that graphically depicts the flight of cannonball advancedadd target class to the cannonball program from the previous problem target should be rectangle placed at random position at the bottom of the window allow users to keep firing until they hit the target redo the regression problem from (programming exercise using regression class your new class will keep track of the various quantities that are needed to compute line of regression (the running sums of xyx and xythe regression class should have the following methods__init__ creates new regression object to which points can be added addpoint adds point to the regression object predict accepts value of as parameterand returns the value of the corresponding on the line of best fit |
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 classes to structure complex data to understand the use of python dictionaries for storing non-sequential collections example problemsimple statistics as you saw in the last classes are one mechanism for structuring the data in our programs classes alonehoweverare not enough to satisfy all of our data-handling needs if you think about the kinds of data that most real-world programs manipulateyou will quickly realize that many programs deal with large collections of similar information few examples of the collections that you might find in modern program includewords in document students in course data from an experiment customers of business graphics objects drawn on the screen cards in deck |
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 the program againaverage py def main()sum count xstr input("enter number to quit>"while xstr !"" eval(xstrsum sum count count xstr input("enter number to quit>"print("\nthe average of the numbers is"sum countmain(this program allows the user to enter sequence of numbersbut the program itself does not keep track of what numbers were entered insteadit just keeps summary of the numbers in the form of running sum that' all that' needed to compute the mean suppose we want to extend this program so that it computes not only the meanbut two other standard statistical measures--median and standard deviation --of the data you are probably familiar with the concept of median this is the value that splits the data set into equal-sized parts for the data the median value is since there are two values greater than and two that are smaller one way to calculate the median is to store all the numbers and put them in order so that we can identify the middle value the standard deviation is measure of how spread out the data is relative to the mean if the data is tightly clustered around the meanthen the standard deviation is small when the data is more spread outthe standard deviation is larger the standard deviation provides yardstick for determining how exceptional value is for examplesome teachers define an "aas any score that is at least two standard deviations above the mean the standard deviationsis defined as ssp ( xi ) - in this formula is the meanxi represents the ith data value and is the number of data values the formula looks complicatedbut it is not hard to compute the expression ( xi ) is the square of the "deviationof an individual item from the mean the numerator of the fraction is the sum of the deviations (squaredacross all the data values |
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 until all of the numbers have been enteredand each individual value as well computing the standard deviation this way requires some method to remember all of the individual values that were entered applying lists in order to complete our enhanced statistics programwe need way to store and manipulate an entire collection of numbers we can' just use bunch of independent variablesbecause we don' know how many numbers there will be what we need is some way of combining an entire collection of values into one object actuallywe've already done something like thisbut we haven' discussed the details take look at these interactive examplesrange( [ "this is an ex-parrot!split(['this''is''an''ex-parrot!'both of these familiar functions return collection of values denoted by the enclosing square brackets these are listsof course lists and arrays as you knowpython lists are ordered sequences of items in factthe ideas and notations that we use for manipulating lists are borrowed from the mathematical notion of sequence mathematicians sometimes give an entire sequence of items single name for instancea sequence of numbers might just be called ss sn- when they want to refer to specific values in the sequencethese values are denoted by subscripts in this examplethe first item in the sequence is denoted with the subscript |
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 to represent an entire sequenceand the individual items in the sequence can be accessed through subscripting wellalmostwe don' have way of typing subscriptsbut we use indexing instead suppose that our sequence is stored in variable called we could write loop to calculate the sum of the items in the sequence like thissum for in range( )sum sum [ivirtually all computer languages provide some sort of sequence structure similar to python' listin other languagesit is called an array to summarizea list or array is sequence of items where the entire sequence is referred to by single name (in this casesand individual items can be selected by indexing ( [ ]arrays in other programming languages are generally fixed size when you create an arrayyou have to specify how many items it will hold if you don' know how many items you will havethen you have to allocate large arrayjust in caseand keep track of how many "slotsyou actually fill arrays are also usually homogeneous that means they are restricted to holding objects of single data type you can have an array of ints or an array of strings but cannot mix strings and ints in single array in contrastpython lists are dynamic they can grow and shrink on demand they are also heterogeneous you can mix arbitrary data types in single list in nutshellpython lists are mutable sequences of arbitrary objects list operations because lists are sequencesyou know that all of the python built-in sequence operations also apply to lists to jog your memoryhere' summary of those operationsoperator len(for in in meaning concatenation repetition indexing length slicing iteration membership check (returns boolean |
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 'yytrue by the waysince we can iterate through liststhe summing example from above can be written more simply and clearly this waysum for in ssum sum recall that one important difference between lists and strings is that lists are mutable you can use assignment to change the value of items in list lst [ lst[ lst[ "hellolst [ 'hello'lst[ lst [ 'hello'lst[ : ["slice""assignment"lst [ 'slice''assignment''hello'as the last example showsit' even possible to change an entire subsequence in list by assigning list into slice python lists are very flexible don' attempt this in other languagesas you knowlists can be created by listing items inside square brackets odds [ food ["spam""eggs""back bacon"silly [ "spam" " "empty [ |
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 numbers typed by the usernums [ input('enter number'while > nums append(xx input("enter number"in essencenums is being used as an accumulator the accumulator starts out emptyand each time through the loop new value is tacked on the append method is just one example of number of useful list-specific methods againfor reviewhere is table that briefly summarizes some things you can do to listmethod append(xsort(reverse(index(xinsert( ,xcount(xremove(xpop(imeaning add element to end of list sort (orderthe list comparison function may be passed as parameter reverse the list returns index of first occurrence of insert into list at index returns the number of occurrences of in list deletes the first occurrence of in list deletes the ith element of the list and returns its value we have seen how lists can grow by appending new items lists can also shrink when items are deleted individual items or entire slices can be removed from list using the del operator mylist [ del mylist[ mylist [ del mylist[ : mylist [ |
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 list can be accessed by indexingand sublists can be accessed by slicing lists are mutableindividual items or entire slices can be replaced through assignment statements lists support number of convenient and frequently used methods lists will grow and shrink as needed statistics with lists now that you know more about listswe are ready to solve our little statistics problem recall that we are trying to develop program that can compute the meanmedianand standard deviation of sequence of numbers entered by the user one obvious way to approach this problem is to store the numbers in list we can write series of functions--meanstddevand median--that take list of numbers and calculate the corresponding statistics let' start by using lists to rewrite our original program that only computes the mean firstwe need function that gets the numbers from the user let' call it getnumbers this function will implement the basic sentinel loop from our original program to input sequence of numbers we will use an initially empty list as an accumulator to collect the numbers the list will then be returned from the function here' the code for getnumbersdef getnumbers()nums [start with an empty list sentinel loop to get numbers xstr input("enter number to quit>"while xstr !"" eval(xstrnums append(xadd this value to the list xstr input("enter number to quit>"return nums using this functionwe can get list of numbers from the user with single line of code data getnumbers(nextlet' implement function that computes the mean of the numbers in list this function takes list of numbers as parameter and returns the mean we will use loop to go through the list and compute the sum |
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 original program to average series of numbers can now be done in two simple linesdef main()data getnumbers(print('the mean is'mean(data)nextlet' tackle the standard deviation functionstddev in order use the standard deviation formula discussed abovewe first need to compute the mean we have design choice here the value of the mean can either be calculated inside of stddev or passed to the function as parameter which way should we do iton the one handcalculating the mean inside of stddev seems cleaneras it makes the interface to the function simpler to get the standard deviation of set of numberswe just call stddev and pass it the list of numbers this is exactly analogous to how mean (and median belowworks on the other handprograms that need to compute the standard deviation will almost certainly need to compute the mean as well computing it again inside of stddev results in the calculations being done twice if our data set is largethis seems inefficient since our program is going to output both the mean and the standard deviationlet' have the main program compute the mean and pass it as parameter to stddev other options are explored in the exercises at the end of the here is the code to compute the standard deviation using the mean (xbaras parameterdef stddev(numsxbar)sumdevsq for num in numsdev xbar num sumdevsq sumdevsq dev dev return sqrt(sumdevsq/(len(nums)- )notice how the summation from the standard deviation formula is computed using loop with an accumulator the variable sumdevsq stores the running sum of the squares of the deviations once this sum has been computedthe last line of the function calculates the rest of the formula finallywe come to the median function this one is little bit trickieras we do not have formula to calculate the median we need an algorithm that picks out the middle value the first step is to arrange the numbers in increasing order whatever value ends up in the middle of the |
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 order if the size of data is oddmedian the middle value elsemedian the average of the two middle values return median this algorithm translates almost directly into python code we can take advantage of the sort method to put the list in order to test whether the size is evenwe need to see if it is divisible by two this is perfect application of the remainder operation the size is even if size = that isdividing by leaves remainder of with these insightswe are ready to write the code def median(nums)nums sort(size len(numsmidpos size / if size = median (nums[midposnums[midpos- ] elsemedian nums[midposreturn median you should study this code carefully to be sure you understand how it selects the correct median from the sorted list the middle position of the list is calculated using integer division as size / if size is then midpos is ( goes into just one timethis is the correct middle positionsince the three values in the list will have the indexes now suppose size is in this casemidpos will be and the four values will be in locations the correct median is found by averaging the values at midpos ( and midpos- ( now that we have all the basic functionsfinishing out the program is cinch def main()print("this program computes meanmedian and standard deviation "data getnumbers(xbar mean(datastd stddev(dataxbarmed median(data |
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 and as general statistical library module here' the complete programstats py from math import sqrt def getnumbers()nums [start with an empty list sentinel loop to get numbers xstr input("enter number to quit>"while xstr !"" eval(xstrnums append(xadd this value to the list xstr input("enter number to quit>"return nums def mean(nums)sum for num in numssum sum num return sum len(numsdef stddev(numsxbar)sumdevsq for num in numsdev num xbar sumdevsq sumdevsq dev dev return sqrt(sumdevsq/(len(nums)- )def median(nums)nums sort(size len(numsmidpos size / if size = median (nums[midposnums[midpos- ] |
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 examples we've looked at so far have involved lists of simple types like numbers and strings howevera list can be used to store collections of any type one particularly useful application is storing collection of records we can illustrate this idea by building on the student gpa data processing program from last recall that our previous grade processing program read through file of student grade information to find and print information about the student with the highest gpa one of the most common operations performed on this kind of data is sorting we might want the list in different orders for different purposes an academic advisor might like to have file with grade information sorted alphabetically by the name of the student to determine which students have enough credit hours for graduationit would be useful to have the file in order according to credit-hours and gpa sort would be useful for deciding which students are in the top of the class let' write program that sorts file of students according to their gpa the program will make use of list of student objects we just need to borrow the student class from our previous program and add bit of list processing the basic algorithm for our program is very simple get the name of the input file from the user read student information into list sort the list by gpa get the name of the output file from the user write the student information from the list into file let' begin with the file processing we want to read through the data file and create list of students here' function that takes filename as parameter and returns list of student |
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 file notice that am borrowing the makestudent function from the gpa programit creates student object from line of the file we will have to be sure to import this function (along with the student classat the top of our program while we're thinking about fileslet' also write function that can write the list of students back out to file remembereach line of the file should contain three pieces of information (namecredit hoursand quality pointsseparated by tabs the code to do this is straightforward def writestudents(studentsfilename)students is list of student objects outfile open(filename' 'for in studentsprint("{ }\ { }\ { }format( getname() gethours() getqpoints())file=outfileoutfile close(notice that used the string formatting method to generate the appropriate line of outputthe \ represents tab character using the functions readstudents and writestudentswe can easily convert our data file into list of students and then write it back out to file all we have to do now is figure how to sort the records by gpa in the statistics programwe used the sort method to sort list of numbers what happens if we try to sort list that contains something other than numbersin this casewe want to sort list of student objects let' try that out and see what happens lst gpasort readstudents("students dat"lst [lst sort(traceback (most recent call last)file ""line in typeerrorunorderable typesstudent(student( |
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 gpain another contextwe may want them in alphabetical order in data processingthe field on which records are sorted is called key to put the students in alphabetical orderwe would use their name as the key for our gpa problemobviouslywe want the gpa to be used as the key for sorting the students the built-in sort method gives us way to specify the key that is used when sorting list by supplying an optional keyword parameterkeywe can pass along function that computes key value for each item in the list sort(keythe key_function must be function that takes an item from the list as parameter and returns the key value for that item in our casethe list item will be an instance of studentand we want to use gpa as the key here' suitable key functiondef use_gpa(astudent)return astudent gpa(as you can see this function simply uses the gpa method defined in the student class to provide the key value having defined this little helper functionwe can use it to sort list of students with call to sort data sort(key=use_gpaan important point to notice here is that did not put parentheses on the function name (use_gpa() do not want to call the function ratheri am sending use_gpa to the sort methodand it will call this function anytime it needs to compare two items to see what their relative ordering should be in the sorted list it' often useful to write this sort of helper function to provide keys for sorting listhoweverin this particular casewriting an additional function is not really necessary we have already written function that computes the gpa for studentit' the gpa method in the student class if you go back and look at the definition of that methodyou'll see that it takes single parameter (selfand returns the computed gpa since methods are just functionswe can use this as our key and save us the trouble of writing the helper in order to use method as standalone functionwe just need to use our standard dot notation data sort(key=student gpathis snippet says to use the function/method called gpa defined in the student class think we now have all the components in place for our program here' the completed codegpasort py program to sort student information into gpa order |
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() getqpoints())file=outfileoutfile close(def main()print("this program sorts student grade information by gpa"filename input("enter the name of the data file"data readstudents(filenamedata sort(key=student gpafilename input("enter name for the output file"writestudents(datafilenameprint("the data has been written to"filenameif __name__ ='__main__'main( designing with lists and classes lists and classes taken together give us powerful tools for structuring the data in our programs let' put these tools to work in some more sophisticated examples remember the dieview class from last in order to display the six possible values of dieeach dieview object keeps track of seven circles representing the position of pips on the face of die in the previous versionwe saved these circles using instance variablespip pip pip etc let' consider how the code looks using collection of circle objects stored as list the basic idea is to replace our seven instance variables with single list called pips our first problem is to create suitable list this will be done in the constructor for the dieview class |
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+offsetcyself pip self __makepip(cx+offsetcy+offsetrecall that __makepip is local method of the dieview class that creates circle centered at the position given by its parameters we want to replace these lines with code to create list of pips one approach would be to start with an empty list of pips and build up the final list one pip at time pips [pips append(self __makepip(cx-offsetcy-offset)pips append(self __makepip(cx-offsetcy)pips append(self __makepip(cx-offsetcy+offset)pips append(self __makepip(cxcy)pips append(self __makepip(cx+offsetcy-offset)pips append(self __makepip(cx+offsetcy)pips append(self __makepip(cx+offsetcy+offset)self pips pips an even more straightforward approach is to create the list directlyenclosing the calls to __makepip inside list construction bracketslike thisself pips self __makepip(cx-offsetcy-offset))self __makepip(cx-offsetcy))self __makepip(cx-offsetcy+offset))self __makepip(cxcy))self __makepip(cx+offsetcy-offset))self __makepip(cx+offsetcy))self __makepip(cx+offsetcy+offset)notice how have formatted this statement rather than making one giant linei put one list element on each line againpython is smart enough to know that the end of the statement has not been reached until it finds the matching square bracket listing complex objects one per line like this makes it much easier to see what is happening just make sure to include the commas at the end of intermediate lines to separate the items of the list the advantage of pip list is that it is much easier to perform actions on the entire set for examplewe can blank out the die by setting all of the pips to have the same color as the background |
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 spot in the pips list in the original programpips and were turned on for the value self pip setfill(self foregroundself pip setfill(self foregroundself pip setfill(self foregroundin the new versionthis corresponds to pips in positions and since the pips list is indexed starting at parallel approach could accomplish this task with these three lines of codeself pips[ setfill(self foregroundself pips[ setfill(self foregroundself pips[ setfill(self foregrounddoing it this way makes explicit the correspondence between the individual instance variables used in the first version and the list elements used in the second version by subscripting the listwe can get at the individual pip objectsjust as if they were separate variables howeverthis code does not really take advantage of the new representation here is an easier way to turn on the same three pipsfor in [ , , ]self pips[isetfill(self foregroundusing an index variable in loopwe can turn all three pips on using the same line of code the second approach considerably shortens the code needed in the setvalue method of the dieview class here is the updated algorithmloop through pips and turn all off determine the list of pip indexes to turn on loop through the list of indexes and turn on those pips we could implement this algorithm using multi-way selection followed by loop for pip in self pipsself pip setfill(self backgroundif value = on [ elif value = on [ , elif value = on [ , , |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.