1

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?

Alex Riley
  • 169,130
  • 45
  • 262
  • 238
jm22b
  • 377
  • 1
  • 3
  • 16
  • take a look at `matplotlib` module python – ZdaR Feb 14 '15 at 12:22
  • Somewhat annoyingly, `randint(a,b)` does **not** use the same argument convention as `range()` or `xrange()`. `randint(a,b)` will return a random integer n: a <= n <= b. So your simulated coin is a bit wonky. :) – PM 2Ring Feb 14 '15 at 12:54

1 Answers1

4

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

Community
  • 1
  • 1
Alex Riley
  • 169,130
  • 45
  • 262
  • 238