Example of top-down design

Notice that the main program is complete, while the rest of the functions are merely stubbed out. The interface of each function has been defined, i.e. how many and what types of parameters are expected as well as what will be returned, but the functions have not yet been implemented. Comments have been included inside the function definitions as reminders for how we expect to implement them.

"""
 This program computes the probability of rolling five of a kind with
 six-sided dice by running a series of simulations and computing
 the average number of rolls required. 

Author: Sally CS Major
Date: Spring 2011
"""

from random import *

def main():
    printIntro()
    numTrials = input("Enter number of simulations to run: ")
    avg = simulate(numTrials)
    print "The average is:", avg
    print "The probabilty is:", 1/avg

# --------------------------------------------------------- #

def printIntro():
    """
    Inputs:  None
    Returns: None
    Purpose: To print an introduction to the user.
    """
    return

# --------------------------------------------------------- #

def simulate(n):
    """
    Inputs:  An integer n representing the number of simulations to run.
    Returns: A float representing the average number of rolls required
             to get five of a kind.
    Purpose: Simulate n trials of rolling dice and compute the average.
    """
    # will call simulateOneTime n times
    return 100.0

# --------------------------------------------------------- #

def simulateOneTime():
    """
    Inputs:  None
    Returns: An integer representing the number of rolls required to
             get five of a kind.
    Purpose: Simulate one trial and count the number of rolls.
    """
    # will call rollDice until the result is allSame
    return 100

# --------------------------------------------------------- #

def rollDice(n):
    """
    Inputs:  An integer n representing the number of dice to roll.
    Returns: A list containing the dice rolls of length n.
    Purpose: Randomly roll n dice. 
    """
    # will call rollOne n times
    return [1] * n

# --------------------------------------------------------- #

def allSame(ls):
    """
    Inputs:  A list of values.
    Returns: True if all the values in the list are the same.
             Otherwise False.
    Purpose: Checks whether the values in a list are equal.
    """
    # will check that each value is equal to the first value
    return True

# --------------------------------------------------------- #

def rollOne():
    """
    Inputs:  None
    Returns: An integer representing the die value between 1 and 6.
    Purpose: Randomly roll one die.
    """
    # will use the random library to simulate a die roll
    return 1

# --------------------------------------------------------- #

main()

Back to the CS21 homepage