Stephen John Elliott
Stephen John Elliott

Reputation: 21

Counting outcomes from a loop?

Created a program which flips a coin 100 times and gives a random outcome for each time. Just wondering if it is possible to count the number of times each outcome appears. No idea where to start. What I have so far....

# A program which flips a coin 100 times and tells you the outcome each time

import random

counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    print (random.choice(flip))

Upvotes: 2

Views: 481

Answers (6)

perreal
perreal

Reputation: 98118

If 1 represents heads, then the number of heads:

import random
print sum(random.choice([0,1]) for x in range(100))
# or more verbose:
print sum('heads' == random.choice(['heads','tails']) for x in range(100))

Upvotes: 7

root
root

Reputation: 80436

You may also want to look at collections.Counter:

Docstring:
Dict subclass for counting hashable items.  Sometimes called a bag
or multiset.  Elements are stored as dictionary keys and their counts
are stored as dictionary values.

In [1]: import random

In [2]: from collections import Counter

In [3]: Counter(random.choice(('heads','tails')) for _ in range(100))
Out[3]: Counter({'heads': 51, 'tails': 49})

Upvotes: 2

TerryA
TerryA

Reputation: 60024

>>> import random
>>> sides = ['heads', 'tails']
>>> headsc = tailsc = 0
>>> for _ in xrange(100):
...     if random.choice(sides) == 'heads':
...         headsc += 1
...     else:
...         tailsc += 1

Upvotes: 1

Mike M&#252;ller
Mike M&#252;ller

Reputation: 85582

sum(random.choice((1, 0)) for x in range(100))

Upvotes: 2

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276586

Here is my take

heads=0
tails=0
for i in range(100):
  if random.randrange(2) == 0:
      heads+=1
  else:
      tails+=1

This is not as clean as a comprehension, but even if you're coming from another language, it's very easy to understand what's going on here.

Upvotes: 2

Geeky Guy
Geeky Guy

Reputation: 9379

Like this:

heads = 0
counter = 0
flip = ["true", "false"]

while counter <= 99:
    counter = counter+1
    print (counter)
    result = random.choice(flip))
    if result == "true":
        heads = heads+1
    print (result)
print ("heads: " + heads)
print ("tails: " + (99 - heads))

Actually my Python is rusty, so I don't know if my syntax is right, but it should be something close to that.

Upvotes: 0

Related Questions