A software development philosophy

First document your code by writing the tests it must satisfy, then write the code.

In python, doctest makes this easy

See the doctest example, then write a program.

Task

Write a function add_dice that takes two lists of values corresponding to the numbers on two dice, and that returns the probability distribution of the sum of the two dice.

Write this function using the doctest approach. First write the documentation, including several examples, such as:

>>> add_dice( [1, 2, 3, 4], [1, 2, 3, 4] )
>>> add_dice( [1, 2, 2, 3], [1, 3, 3, 5] )
>>> add_dice( [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6] )

You might find the convolve function useful when solving this problem. See this page for example functions using scipy.convolve. But it's not essential to use convolve.

When you have written your program, check that you get the correct answer for the solution to Alan's problem, find another labelling of two six-sided dice, such that the sum has the same distribution as add_dice( [1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 5, 6] ) .


Further examples

DocExample2.py


Worked solution

AlanDice.py

AlanDice2.py


Other python examples

DocExample.py

#!/usr/bin/python
#
#  Example showing how to use doctest
#

def square( x ):
    """
    The square function returns   x * x
    >>> square(3)
    9
    >>> square(-1)
    1
    """
    return x*x

if __name__ == '__main__':
    import doctest
    verbose=1
    if(verbose):
        doctest.testmod(None,None,None,True)
    else:
        doctest.testmod()