Not logged in. Login

Exercise 9

Testing the Random Number Generator

I have some beliefs about what happens when you roll two dice, but would like to test them.

In random_histogram.py, we'll roll several pairs of dice and draw a simple histogram of the results.

  • sum_two_dice(): should generate two random integers 1 to 6 and return their sum.
  • roll_dice(num): should roll num pairs of dice (by calling sum_two_dice) and counting the number of 2s, 3s, 4s, ..., 12s rolled. It should return a list of the count of each roll that occurred (i.e. a list of ≈12 elements that would sum to num).
  • draw_histogram(counts): that takes the counts produced by the previous function, creates and image, draws the histogram (using ImageDraw methods), and returns and Image like this:
    def draw_histogram(counts):
        img = Image.new("RGB", (img_width, img_height))
        ...
        return img
    

The main part of your program should be only imports and:

rolls = 1000
img_width = 325
img_height = 250
y_per_count = 1000 / rolls
x_per_bar = 25
y_base = 230
x_base = 25

counts = roll_dice(rolls)
img = draw_histogram(counts)
img.save("histo.png")

The constants defined here mean the rectangle for the "number of t rolled" will have:

  • x coordinates from x_base + (t - 2) * x_per_bar (left) to x_base + (t - 1) * x_per_bar (right) and
  • y coordinates from y_base (bottom) to y_base - counts[t] * y_per_count (top).

This was the output of one run of my program:

Modifying Lists

For this question, in chop.py you will create two similar functions that actually work very differently. Both of these functions will be used to remove the last item from a list, but will operate in different ways.

Write a function chop1 that returns its argument with the last item removed. It should not change the argument, but should return a copy without the last item.

>>> testlist = [0,1,2,3,4]
>>> chop1(testlist) # note: returns modified copy
[0, 1, 2, 3]
>>> print(testlist) # note: original unchanged
[0, 1, 2, 3, 4]

Write a function chop2 that removes the last item from a list given as its argument. The existing list should be changed in-place; the function should not return anything.

>>> testlist = [0,1,2,3,4]
>>> chop2(testlist) # note: no return value
>>> print(testlist)
[0, 1, 2, 3]

The difference between these two functions is important. The first operates like all of the other functions we've written: taken arguments and returned whatever results it created. The second is possible because lists are mutable: the function takes the reference to the list and changes it in-place.

Submitting

Submit all of your work through CourSys.

Updated Thu July 04 2024, 13:25 by ggbaker.