Python code for the coin toss issues

2019-06-18 22:03发布

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?

10条回答
时光不老,我们不散
2楼-- · 2019-06-18 22:34
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)
查看更多
何必那么认真
3楼-- · 2019-06-18 22:34

I ended up with this.

import random

flips = 0
heads = 0
tails = 0

while flips < 100:
    flips += 1

    coin = random.randint(1, 2)
    if coin == 1:
       print("Heads")
       heads += 1

    else:
       print("Tails")
       tails += 1

total = flips

print(total, "total flips.")
print("With a total of,", heads, "heads and", tails, "tails.")
查看更多
Bombasti
4楼-- · 2019-06-18 22:41
tosses = 100
heads = sum(random.randint(0, 1) for toss in range(tosses))
tails = tosses - heads
查看更多
ら.Afraid
5楼-- · 2019-06-18 22:43
>>> import numpy as np
>>> coins = np.random.randint(2, size=100)
>>> print('Heads: ', np.sum(coins))
('Heads: ', 44)
>>> print('Tails: ', 100 - np.sum(coins))
('Tails: ', 56)
>>> print(['H' if i==1 else 'T' for i in coins])
['T', 'T', 'T', 'T', 'T', 'H', 'T', 'T', 'H', 'H', 'H', 'T', 'T', 'H', 'H', 'T', 'T', 'H', 'H', 'H', 'T', 'T', 'H', 'H', 'H', 'H', 'H', 'H', 'T', 'H', 'H', 'T', 'T', 'T', 'T', 'T', 'H', 'T', 'T', 'T', 'H', 'H', 'H', 'T', 'T', 'T', 'T', 'T', 'H', 'T', 'H', 'H', 'H', 'T', 'H', 'T', 'H', 'T', 'H', 'T', 'T', 'T', 'H', 'H', 'T', 'T', 'H', 'T', 'T', 'H', 'H', 'T', 'T', 'T', 'T', 'H', 'T', 'H', 'H', 'H', 'T', 'H', 'T', 'H', 'T', 'H', 'T', 'T', 'T', 'T', 'T', 'T', 'H', 'H', 'T', 'T', 'T', 'H', 'H', 'T']
查看更多
登录 后发表回答