【问题标题】:Python code for the coin toss issues抛硬币问题的 Python 代码
【发布时间】:2011-09-23 03:11:21
【问题描述】:

我一直在用 python 编写一个程序,模拟 100 次抛硬币并给出抛硬币的总数。问题是我还想打印正面和反面的总数。

这是我的代码:

import random
tries = 0
while tries < 100:
    tries += 1
    coin = random.randint(1, 2)
    if coin == 1:
        print('Heads')
    if coin == 2:
        print ('Tails')
total = tries
print(total)

我一直在绞尽脑汁寻找解决方案,但到目前为止我一无所获。除了投掷的总次数之外,还有什么方法可以打印出正面和反面的数量?

【问题讨论】:

  • 如何在每个 if-case 中添加一个计数器(一个用于正面,一个用于反面)?
  • 与计数尝试相同...但仅在打印头时计数。像heads += 1 这样的东西将是门票:-)
  • 查看“tries”变量的作用,并尝试使用“heads”和“tails”变量来复制它。但是不要每次都做heads+=1...你自己搞定的!

标签: python random statistics coin-flipping


【解决方案1】:
import random

samples = [ random.randint(1, 2) for i in range(100) ]
heads = samples.count(1)
tails = samples.count(2)

for s in samples:
    msg = 'Heads' if s==1 else 'Tails'
    print msg

print "Heads count=%d, Tails count=%d" % (heads, tails)

【讨论】:

  • +1 这更接近于我们通常在 Python 中做事的方式。释放你的心灵;不要试图一步一步地考虑事情,因为正如你向自己证明的那样,这并不容易。想想你想要完成的事情:“我想要一个 100 次掷硬币的序列;我想要按顺序输出‘正面’或‘反面’;我想要显示正面和反面的计数”。
  • 我希望 op 尝试构建它几次。在这里(第 3 行)对推导进行了很好的介绍。
  • 几件事。 (1) 循环计数器i 没有被读取,所以你可以写:samples = [random.randint(1, 2) for _ in range(100)]。 (2) 您可以使用查找表查找结果:messages = {1: "Heads", 2: "Tails"} for s in samples: print messages[s] (3) 可能是枚举的好地方:for i, s in enumerate(samples): print i, messages[s]
【解决方案2】:

你有一个尝试次数的变量,它允许你在最后打印它,所以只需对正面和反面的数量使用相同的方法。在循环外创建headstails 变量,在相关的if coin == X 块内递增,然后在最后打印结果。

【讨论】:

  • P'sao 的答案有代码,但你有解释。我要感谢你和 P'sao。
【解决方案3】:
import random

total_heads = 0
total_tails = 0
count = 0


while count < 100:

    coin = random.randint(1, 2)

    if coin == 1:
        print("Heads!\n")
        total_heads += 1
        count += 1

    elif coin == 2:
        print("Tails!\n")
        total_tails += 1
        count += 1

print("\nOkay, you flipped heads", total_heads, "times ")
print("\nand you flipped tails", total_tails, "times ")

【讨论】:

    【解决方案4】:

    跟踪磁头数量:

    import random
    tries = 0
    heads = 0
    while tries < 100:
        tries += 1
        coin = random.randint(1, 2)
        if coin == 1:
            heads += 1
            print('Heads')
        if coin == 2:
            print ('Tails')
    total = tries
    print('Total heads '.format(heads))
    print('Total tails '.format(tries - heads))
    print(total)
    

    【讨论】:

      【解决方案5】:
      import random
      tries = 0
      heads=0
      tails=0
      while tries < 100:
          tries += 1
          coin = random.randint(1, 2)
          if coin == 1:
              print('Heads')
              heads+=1
          if coin == 2:
              print ('Tails')
              tails+=1
      total = tries
      print(total)
      print tails
      print heads
      

      【讨论】:

      • 是的,这是对 OP 代码的最小更改。不过,这并不是真正地道的 python。
      【解决方案6】:
      tosses = 100
      heads = sum(random.randint(0, 1) for toss in range(tosses))
      tails = tosses - heads
      

      【讨论】:

        【解决方案7】:

        您可以使用random.getrandbits() 一次生成所有 100 个随机位:

        import random
        
        N = 100
        # get N random bits; convert them to binary string; pad with zeros if necessary
        bits = "{1:>0{0}}".format(N, bin(random.getrandbits(N))[2:])
        # print results
        print('{total} {heads} {tails}'.format(
            total=len(bits), heads=bits.count('0'), tails=bits.count('1')))
        

        Output

        100 45 55
        

        【讨论】:

        • 嗯。我不知道random.getrandombits
        【解决方案8】:
        # Please make sure to import random.
        
        import random
        
        # Create a list to store the results of the for loop; number of tosses are limited by range() and the returned values are limited by random.choice().
        
        tossed = [random.choice(["heads", "tails"]) for toss in range(100)]
        
        # Use .count() and .format() to calculate and substitutes the values in your output string.
        
        print("There are {} heads and {} tails.".format(tossed.count("heads"), tossed.count("tails")))
        

        【讨论】:

        • 你实际上并没有回答这个问题 - 你没有计算头部或尾部抛掷的次数。
        • @cha0site 我不明白你对这个问题的解释。此代码计算正面和反面的数量。运行代码看看。
        【解决方案9】:

        我最终得到了这个。

        import random
        
        flips = 0
        heads = 0
        tails = 0
        
        while flips < 100:
            flips += 1
        
            coin = random.randint(1, 2)
            if coin == 1:
               print("Heads")
               heads += 1
        
            else:
               print("Tails")
               tails += 1
        
        total = flips
        
        print(total, "total flips.")
        print("With a total of,", heads, "heads and", tails, "tails.")
        

        【讨论】:

          【解决方案10】:

          这是我的代码。希望它会有所帮助。

          import random
          
          coin = random.randint (1, 2)
          
          tries = 0
          heads = 0
          tails = 0
          
          while tries != 100:
          
          if coin == 1:
              print ("Heads ")
              heads += 1
              tries += 1
              coin = random.randint(1, 2)
          
          elif coin == 2:
              print ("Tails ")
              tails += 1
              tries += 1
              coin = random.randint(1, 2)
          else:
              print ("WTF")
          
          print ("Heads = ", heads)
          print ("Tails = ", tails)
          

          【讨论】:

          • 这几乎是c/p的答案,OP的问题已经回答了。
          【解决方案11】:
          import random
          
          print("coin flip begins for 100 times")
          
          tails = 0
          heads = 0
          count = 0
          while count < 100: #to flip not more than 100 times
          count += 1
          result = random.randint(1,2) #result can only be 1 or 2.
          
              if result == 1: # result 1 is for heads
                  print("heads")
              elif result == 2: # result 2 is for tails
                  print("tails")
              if result == 1:
                  heads +=1 #this is the heads counter.
              if result == 2:
                  tails +=1 #this is the tails counter.
          # with all 3 being the count, heads and tails counters,
          # i can instruct the coin flip not to exceed 100 times, of the 100 flips 
          # with heads and tails counter, 
          # I now have data to display how of the flips are heads or tails out of 100.
          print("completed 100 flips") #just to say 100 flips done.
          print("total tails is", tails) #displayed from if result == 2..... tails +=1
          print("total heads is", heads)
          

          【讨论】:

          • 也许你可以给它添加一些解释,而不是仅仅发布一段代码
          • 我很抱歉。我在我的代码中添加了 cmets 来解释我的逻辑。希望对您有所帮助。
          • 上面的代码是在100次硬币翻转中显示正面或反面。它添加了正面和反面计数器,因此在 100 次硬币翻转中,我能够知道有多少是正面或反面。最后打印结果以显示计数。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-04
          • 1970-01-01
          • 2021-02-22
          • 2016-03-28
          • 1970-01-01
          • 2014-05-25
          • 1970-01-01
          相关资源
          最近更新 更多