Exploring Python Exercise
Question: I am learning Python from the book _Exploring Python_ by Timothy Budd. One of
the exercises from this chapter is this:

15. The function `randint` from the random module can be used to produce random numbers. A call on `random.randint(1, 6)`, for example, will produce the values 1 to 6 with equal probability. Write a program that loops 1000 times. On each iteration it makes two calls on `randint` to simulate rolling a pair of dice. Compute the sum of the two dice, and record the number of times each value appears. Afterthe loop, print the array of sums. You can initialize the array using the idiom shown earlier in this chapter:

`times = [0] * 12 # make an array of 12 elements, initially zero`

I am able to print the sum in the array, but I have not understood the concept
of recording the number of times each value appears. Also, what purpose would
`times = [0]` serve? Here is my code for printing the sum:

    
    
     #############################################
    #   Program to print the sum of dice rolls  #
    #############################################
    
    from random import randint
    import sys
    
    
    times = [0] * 12
    
    summation = []
    
    def diceroll():
    
        print "This program will print the"
        print "sum of numbers, which appears"
        print "after each time the dice is rolled."
        print "The program will be called 1000 times"
    
    
    
        for i in range(1,1000):
    
            num1 = randint(1,6)
            num2 = randint(1,6)
    
            sum = num1 + num2
            summation.append(sum)
            #times[i] = [i] * 12
        print summation
        #print times
    
    
    diceroll()
    


Answer: `times[0] * 12` initiates a list of 12 elements with value 0. What you want to
do next is

    
    
    times[s] += 1 #adds 1 to the number of times s occurs
    

This is similar to using a dict to encode a value, but its simpler.

`times = [0]` initializes a list called times of length 1 and value 0. The
idiom `times = [0] * 12` means times is a list of 12 zeroes.

If you want to be able to use this without keyerror when `num1==num2==6`, you
need to do `times = [0]*13` because python is a 0 indexed system.

Sidenote: Don't use `sum` as a variable name because it is a builtin function
(predefined) and you don't want to override it. Use `times[sum([num1,num2])]
+= 1` or `times[num1+num2]` instead.

