Search code examples
pythonmatplotlibpresentation

Tallying the outcome of a coin flip


I have written a little piece of code for modelling the outcome of a coin flip, and would like to find a better way of presenting the results than a list of consecutive coin flips. I'm one month into learning Python as part of my physics degree, if that helps provide some context.

Here's the code;

from pylab import *

x=0
while x<=100:

    num = randint(0,2)
    if num == 0:
        print 'Heads'
    else:
        print 'Tails'
    x=x+1
print 'Done'

What options do I have to present this data in an easier to interpret manner?


Solution

  • Instead of using a while loop and printing results to the screen, Python can do the counting and store the results very neatly using Counter, a subclass of the built in dictionary container.

    For example:

    from collections import Counter
    import random
    
    Counter(random.choice(['H', 'T']) for _ in range(100))
    

    When I ran the code, it produced the following tally:

    Counter({'H': 52, 'T': 48})
    

    We can see that heads was flipped 52 times and tails 48 times.

    This is already much easier to interpret, but now that you have the data in a data structure you can also plot a simple bar chart.

    Following the suggestions in a Stack Overflow answer here, you could write:

    import matplotlib.pyplot as plt
    
    # tally = Counter({'H': 52, 'T': 48})
    
    plt.bar(range(len(tally)), tally.values(), width=0.5, align='center')
    plt.xticks(range(len(tally)), ['H', 'T'])
    plt.show()
    

    This produces a bar chart which looks like this:

    enter image description here