python - 当头数=尾巴数时停止的无限硬币翻转

时间:2014-10-03 08:34:35

标签: python flip coin-flipping

我是python的新手,我正在尝试创建一个coinflip循环,它将继续翻转并计算翻转次数,直到磁头数量=尾部数量,它将停止并打印总数转过来达到那个目的。我正在尝试获得结果,以便完成我的数学课程,但我似乎无法弄清楚如何让它停止或打印结果,当我这样做打印0。这是我有的代码所以远:

import random
heads = 1
tails = sum(random.choice(['head', 'tail']) == 'tail'
count = 0
while True:
    coinresult = random.randint(1, 2) if heads == tails:
    break

print("The number of flips was {count}".format(count = heads + tails))

3 个答案:

答案 0 :(得分:1)

不确定你的缩进是怎么回事,但试试这个:

import random
heads = 0 #initialize the count variables
tails = 0

while True:
    coinresult = random.randint(1, 2) #flip coin
    if coinresult == 1: #if result = 1 then increment heads counter
        heads += 1
    elif coinresult == 2: #if result = 2 then increment tails counter
        tails += 1
    if heads == tails: #check if counts are equal and break loop if they are
        break

print("The number of flips was {count}".format(count = heads + tails))

答案 1 :(得分:0)

import itertools as it
import random

def flips():
    while True:
        yield (random.getrandbits(1)<<1) - 1

def cumsum(seq):
    s = 0
    for i in seq:
        s += i
        yield s

def length(seq):
    n = 0
    for _ in seq:
        n += 1
    return n

print("The number of flips was {}".format(length(it.takewhile((0L).__cmp__, cumsum(flips())))))

答案 2 :(得分:0)

我认为这将是一个不错的实现

import random

s = 0
iteration = 0
while True:
    coin = random.sample([-1,1], 1)[0]
    s = s + coin
    iteration = iteration + 1
    if s == 0:
        break

print(iteration)