【问题标题】:python - infinite coin flip that stops when number of heads = number of tailspython - 当正面数量=反面数量时停止的无限硬币翻转
【发布时间】:2014-10-03 08:34:35
【问题描述】:

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

【问题讨论】:

  • 您实际上是在进行随机游走。它可能需要很长时间才能终止。我运行了 James Kent 的算法 20 次,并且在数千次中进行了两次步行。
  • 我递归地跑了 100 次,平均跑了 360 次,正如你所说的最高的是数千次​​pan>

标签: python flip coin-flipping


【解决方案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))

【讨论】:

    【解决方案2】:
    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())))))
    

    【讨论】:

      【解决方案3】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2019-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多