Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python code for the coin toss issues

I've been writing a program in python that simulates 100 coin tosses and gives the total number of tosses. The problem is that I also want to print the total number of heads and tails.

Here's my code:

import random
tries = 0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
    if coin == 2:
        print ('Tails')
total = tries
print(total)

I've been racking my brain for a solution and so far I have nothing. Is there any way to get the number of heads and tails printed in addition to the total number of tosses?

like image 554
Ru1138 Avatar asked Jun 26 '11 21:06

Ru1138


People also ask

How do you flip a coin 100 times in python?

#Program to flip coin 100 times. import random y=1 x=100 head=0 tail=0 while y<=x: coin=random. randrange(2)+1 if coin==2: head+=1 elif coin==1: tail+=1 if y<=x: y+=1 print ("head= "),head print ("tail= "),tail print ("Press Enter to exit!

Can you control the outcome of a coin toss?

It is very hard to control the outcome of a coin flip. The trick can only work by taking into account the environment (i.e. the wind, surface properties etc.) and making a computer model of them. In quantum physics this could for example be temperature fluctuations.


1 Answers

import random

samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print msg

print "Heads count=%d, Tails count=%d" % (heads, tails)
like image 150
pajton Avatar answered Oct 06 '22 23:10

pajton