coin toss in python, flips coin 1000 times, need to run it 3 times and find average [closed]

StackOverflow https://stackoverflow.com/questions/12486514

  •  02-07-2021
  •  | 
  •  

質問

Here is what I have so far. The problem asks us to run coinToss(1000) a certain number of times. Then find the average number of heads based on the three times it ran. (e.g., If we got 400 heads, 350 heads, and then 600 heads, the program would return 450 heads as the average of the three.) I am stumped here, as I can't figure out how to get this thing to run three times, and return the average. Any help would be greatly appreciated!

import random

def coinToss(number):

    heads = 0
    tails = 0
    for i in range(0, number):
        flip = int(random.random()*2)
        if (flip == 0):
            heads = heads + 1
        else:
            tails = tails + 1
    return (heads, tails)

def simulatecoinToss(counter):

    for i in range(0, counter):
        coinToss(1000)
        counter = counter -1
    return 
役に立ちましたか?

解決

simulateCoinToss(counter,number):
    trial_heads = (coinToss(number)[0] for _ in xrange(counter))
    average_heads = float(sum(trial_heads))/counter
    return (average_heads, number-average_heads)

Note: you don't actually need to record anything about tails (as heads+tails=number).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top