【问题标题】:Why does this total not amount to 1000?为什么这个总数不等于 1000?
【发布时间】:2017-06-27 13:18:01
【问题描述】:

当我运行下面的程序时,总数不是1000。我不知道出了什么问题。

在 1000 次掷骰子中,有:

  • 180 换 1
  • 136 为 2
  • 121 为 3
  • 97 为 4
  • 72 为 5
  • 60 换 6。

这总共是 666 次骰子。

我想具体一点,如果有什么我不清楚的地方,请告诉我。谢谢大家:)

#this is a program that simulate how many times that there will be for every sides of a dice, when I trying to throw it 1,000 times.

from random import randrange

def toss():
    if randrange(6) == 0:
        return "1"
    elif randrange(6) ==1:
        return "2"
    elif randrange(6) ==2:
        return "3"
    elif randrange(6) ==3:
        return "4"
    elif randrange(6) ==4:
        return "5"
    elif randrange(6) ==5:
        return "6"

def roll_dice(n):
    count1 = 0
    count2 = 0
    count3 = 0
    count4 = 0
    count5 = 0
    count6 = 0
    for i in range(n):
        dice = toss()
        if dice == "1":
            count1 = count1 + 1
        if dice == "2":
            count2 = count2 + 1
        if dice == "3":
            count3 = count3 + 1
        if dice =="4":
            count4 = count4 + 1
        if dice == "5":
            count5 = count5 + 1
        if dice == "6":
            count6 = count6 + 1
    print ("In", n, "tosses of a dice, there were", count1, "for 1 and", 

count2, "for 2 and", count3, "for 3 and", count4, "for 4 and", count5, "for
 5 and",count6, "for 6.")

roll_dice(1000)

【问题讨论】:

  • 尝试将其更改为 def toss(): return randrange(6) + 1; 和 for i in range(n): i = toss(); count[i] = count.get(i, 0) + 1; 之类的名称,以减轻我的眼睛伤害
  • SO 是一个糟糕的调试器。你试过什么?

标签: python random simulation


【解决方案1】:

您在所有if/elif 测试中都调用了randrange(6),因此值不同(它是随机),您最终可能会从toss 函数返回None(而且你错过了一些计数)

将randrange(6) 存储在一个变量中,然后对其进行测试。

有更好的方法来做这个顺便说一句,例如一个等效但有效的方法:

def toss():
    return str(randrange(6)+1)

但是有一个更快的方法使用 collections.Counter 和生成器理解来随机生成从 1 到 6 的 1000 个值:

import collections
import random
c = collections.Counter(random.randint(1,6) for _ in range(1000))
print(c)
print(sum(c.values()))

我得到了那两条输出线(首先是计算数字和总卷数的字典):

Counter({3: 199, 2: 172, 1: 160, 5: 160, 4: 158, 6: 151})
1000

现在我有 1000 个值了 :)

【讨论】:

    【解决方案2】:

    因为它在每种情况下都会再次调用该函数。

    if randrange(6) == 0:
    

    如果不为 0,则继续第二个 if,其中 randrange(6) 将再次调用一个新值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多