Python - 公平地掷骰子并计算我得到了多少个 4

Python - rolling a dice fairly and counting how many 4's I get

所以我必须编写代码来公平地掷骰子并计算我得到了多少个 4。在你们所有人的帮助下,我开始工作了。那么现在我必须创建另一个模具并滚动它们,然后将它们的产品加在一起。这是我得到的指示。

"Then write another function that simulates rolling two fair dice. The easy way is to call the function you just wrote, twice, and add the numbers you get. This should return a number between 2 and 12. It should calculate BOTH numbers in ONE run – you are counting two distinct things."

这是我刚刚修复的代码。

from random import randrange
def roll():
    rolled = randrange(1,7)
    if rolled == 1:
        return "1"
    if rolled == 2:
        return "2"
    if rolled == 3:
        return "3"
    if rolled == 4:
        return "4"
    if rolled == 5:
        return "5"
    if rolled == 6:
        return "6"


def rollManyCountTwo(n):
    twoCount = 0
    for i in range (n):
        if roll() == "2":
            twoCount += 1
    print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")

rollManyCountTwo(6000)

您的代码很糟糕,因此没有达到应有的随机性。

randrange(low,up) 包括两个边界。

看看你在roll函数中做了什么:

你掷骰子。如果是1,你return"1"。 如果不是1,你再掷一次骰子!那是完全错误的,在游戏中会被视为作弊。

你的翻滚功能完全没有必要,可以用 str(randrange(1,6)).

此外,为什么需要数字作为字符串?您实际上并没有使用这些字符串,所以只使用 randrange 的结果——一个数字。

编辑:

你说

Yeah I'm assuming some of it is unnecessary but it's for a class and this is the way he wants it so I'm trying to keep it how he wants. I thought that's what I was doing but I could find a way around it!

这一切都是不必要的。有一个函数可以满足您的需求,因此无需将其封装在 class 中。

嗯,你可以

class ash_class(object):
    def roll():
        return str(randrange(1,6))

对于您的计数问题:Python 包含所有工具。

counts = [0] * 6 # this is [0,0,0,0,0,0]
for i in range(n):
    counts[randrange(1,6)] += 1
print counts

如您所见,如果随机数是 numbers 而不是字符串,那将非常方便,因为您可以像 numbers 一样使用它们索引一个数组。

作为个人建议:应该始终有讨论糟糕设计选择的自由。一个这样糟糕的设计选择是迫使您将数字转换为字符串,而您显然需要将它们作为数字使用。

您不应该在每个 if 条件下在 roll() 中调用 randrange(),而是应该调用一次并将其保存在变量中并检查。

代码看起来像 -

from random import randrange
def roll():
    rolled = randrange(1,7)
    if rolled == 1:
        return "1"
    if rolled == 2:
        return "2"
    if rolled == 3:
        return "3"
    if rolled == 4:
        return "4"
    if rolled == 5:
        return "5"
    if rolled == 6:
        return "6"


def rollManyCountFour(n):
    fourCount = 0
    for i in range (n):
        if roll() == "6":
            fourCount += 1
    print ("In", n,"rolls of a due, there were",fourCount,"fours.")

rollManyCountFour(6000)

我使用了 np.random.randint(1, 7, N),其中 N 是卷数,并使用了以下系统来存储它(如果这有帮助的话):

R1s = 0
R2s = 0
R3s = 0
R4s = 0
R5s = 0
R6s = 0
for i in range(0, N):
    if x[i] == 1:
        R1s += 1
    elif x[i] == 2:
        R2s += 1
    elif x[i] == 3:
        R3s += 1
    elif x[i] == 4:
        R4s += 1
    elif x[i] == 5:
        R5s += 1
    else:
        R6s += 1

print(R1s)
# Ans ≈ N/6