掷 4 个骰子 1000 次并计算四个骰子点数之和等于或高于 21 的次数

Rolling 4 dices 1000 times and counting the number of times the sum of the four dices' score is equal to 21 or higher

所以,我正在 Python 学习随机化,并想通过制作一种“骰子模拟器”程序来测试我的知识,该程序可以抛出四个“骰子”1000 次;然后计算四个骰子的总和等于或大于 21 的次数。这是我到目前为止所得到的:

import random

dice1 = random.randint(1,6)
dice2 = random.randint(1,6)
dice3 = random.randint(1,6)
dice4 = random.randint(1,6)

sum = dice1 + dice2 + dice3 + dice4

n = 0    # the amount of times the sum of the score was 21 or higher

for i in range(1000):
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)

    for sum >= 21:
        n = n + 1

print("You got 21 or higher", n, "times.")

但是,程序的结果 window 仅显示 “您获得 21 或更高 0 次。”“您获得 21 或更高1000 次。”。所以,我想我的问题是:如何修复代码,以便它计算在 1000 次“掷骰子”中得分总和为 21 或更高的次数,并在结果中打印所述次数 window,以及我代码中的哪一行需要修复(又名:哪里出错了)?提前致谢!

你不需要定义骰子,每个 random.randint(1,6) 本身就是一个骰子。

import random

n = 0    # the amount of times the sum of the score was 21 or higher

for i in range(1000):
    sum = random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6)

    if sum >= 21:
        n = n+1

print("You got 21 or higher", str(n), "times.")

这是一个pythonic方式:

dice_sum = [int((x/x)) for x in range(1,1001) if  random.randint(1,6) + random.randint(1,6) + random.randint(1,6) + random.randint(1,6) >= 21]

print("You got 21 or higher", str(sum(dice_sum)), "times.")

我所做的就是每次骰子为 >= 21 时获取索引,然后将其除以相同的索引,使其 returns 1 到列表中,然后我得到总和列表,也就是 1 被添加到列表中的次数,也就是骰子出现的次数 >= 21.

您需要在 for 循环中计算骰子的总和。

在您的示例中,总和始终等于前 4 次调用 random.randint 时生成的随机数的总和,但您应该每次都重新计算总和。

此外,在 for sum >= 21 行中,for 应替换为 iffor用于重复,if用于条件执行。

您应该在 for 循环中更新变量 sum。否则,它保持其初始值,即第一次掷骰中四个骰子的总和。

请注意,它们是一个名为 sum 的 python 内置函数,为变量使用内置名称是非常糟糕的做法。下面,我将变量重命名为 sumOfDice.

import random

n = 0    # the amount of times the sum of the score was 21 or higher

for i in range(1000):
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)
    
    sumOfDice = dice1 + dice2 + dice3 + dice4
    
    if sumOfDice >= 21:
        n = n + 1

print("You got 21 or higher", n, "times.")

其他改进

当您开始使用名称中包含数字的变量时,您应该问问自己:骰子真的需要四个命名变量吗?使用一个列表来保存四个值不是更容易吗?如果 dice 是一个列表,那么您可以通过 dice[0]dice[1] 等方式访问各个值。但是您也可以使用循环列表理解和其他很酷的 python 功能来操纵列表。您甚至可以调用 python 内置函数 sum 来获取列表的总和!!

import random
n = 0
for i in range(1000):
    dice = [random.randint(1,6) for _ in range(4)]
    if sum(dice) >= 21:
        n = n + 1
print("You got 21 or higher, {} times.".format(n))

我解决了这个问题。你能试试这个吗

import random

n = 0   

for i in range(1000):
    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)
    sum = dice1 + dice2 + dice3 + dice4
    if sum >= 21:
        n = n + 1

print("You got 21 or higher", n, "times.")