$ cd $ cd cs21/inclass $ pwd /home/your_user_name/cs21/inclass $ mkdir w07-design $ cd w07-design $ pwd /home/your_user_name/cs21/inclass/w07-design $ cp ~adanner/public/cs21/w07-design/* . $ ls
Think about the answers to the following questions. Feel free to modify the program or use the python shell to help you answer these questions.
When you use top-down design, your resulting program's structure should closely match that of the steps: the main function should have calls to a few high-level functions, usually one for each high-level step; high-level functions have calls to functions that implement sub-steps of the high-level step; and so on.
Program functions also come from recognizing part of the code (or recongizing steps in the algorithm) where that are similar to other parts and generalizing that functionality into a function.
def squareRoot(num): """ This function computes the square root of a number. num: the number returns: the square root of num """ print "inside squareRoot num is", num # TODO: implement this function return 1
We are going to try applying Top-Down Design and Iterative Refinement to write a program that computes the winning percentage of the game of Craps by simulating some number of games and keeping track of the number won.
The game of Craps is played as follows:
A player rolls a pair of six-sided dice.
If the initial roll is 2, 3, or 12, the player loses.
If the initial roll is 7 or 11, the player wins.
Any other initial roll causes the player to "roll for points". This means that the player keeps rolling either until s/he re-rolls the initial value (a win) or rolls a 7 (a loss).
Write a program to simulate multiple games of craps and estimate the probability that the player wins.
At this point we could start writing the code for the main function, its code will look like calls to functions, each one implementing one of these high-level steps. We will add function stubs for the functions implementing these high-level steps to test our our main program's control flow.
Let's think about input and return values for functions we would write for these steps ((1) getPositiveInt (2) playGamesOfCraps (3) we likely don't need a function for this step (it consists of just one python instruction). We will just add the code to do this step directly to main.
Let's open craps.py, which contains code for this first step and test our program's control flow.
Next we will refine step (2) Play some number of games of craps, into sub-steps, and so on.
As we write individual functions, we can test them out independently of how they will be called in the final program by making test calls to them from main (or another function) passing in different test values and seeing if they return the correct values and do the right thing. Once we have tested them for correctness, we will remove these test calls.