1

我是 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))
4

3 回答 3

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))
于 2014-10-03T08:38:28.720 回答
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())))))
于 2014-10-03T09:29:33.137 回答
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)
于 2014-10-03T09:53:59.843 回答