Python抛硬币

And*_*ndy 2 python random

我是Python的新手,我无法解决这个问题.我有以下功能定义:

def FlipCoins(num_flips):
    heads_rounds_won = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
    return heads_rounds_won
Run Code Online (Sandbox Code Playgroud)

它应该做什么(但显然不是):翻转硬币num_flip次数,计算头部和尾部,看看是否有更多的头部而不是尾部.如果是,则递增head_rounds_won1.重复10000次.

我认为这head_rounds_won将约为5000(50%).并且它将奇数作为输入.例如,3,5或7将产生约50%.然而,偶数会产生更低的结果,更像是34%.特别是小数字,偶数更高,例如800,差异达到50%要窄得多.

为什么会这样?不应该有任何输入产生约50%的头/尾?

mit*_*tch 9

你刚刚得到很多并列的回合

def FlipCoins(num_flips):
    heads_rounds_won = 0
    tails_rounds_won = 0
    tied_rounds = 0
    for i in range(10000):
        heads = 0
        tails = 0
        for j in range(num_flips):
            dice = random.randint(0,1)
            if dice==1: heads += 1
            else: tails += 1
        if heads > tails: heads_rounds_won += 1
        elif heads < tails: tails_rounds_won+= 1
        else: tied_rounds += 1
    return heads_rounds_won, tails_rounds_won, tied_rounds
Run Code Online (Sandbox Code Playgroud)

将返回类似的东西

>>> FlipCoins(2)
(2506, 2503, 4991)
Run Code Online (Sandbox Code Playgroud)