如何解决将4个骰子滚动1000次并计算四个骰子的总和等于21或更高的次数
因此,我正在学习使用Python进行随机化的方法,并希望通过制作一种“骰子模拟器”程序来测试我的知识,该程序会抛出4次“骰子” 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.")
但是,程序的结果窗口仅显示“您获得21次或以上0次。” 或“您获得21次或以上1000次。” 。因此,我想我的问题是:如何修正代码,以便计算出1000次“骰子投掷”中得分总和等于21或更高的次数,并在结果窗口中显示上述次数,以及我的代码中需要修复的几行(又名:哪里出了问题)?预先感谢!
解决方法
您应该在sum
循环内更新变量for
。否则,它将保留其初始值,即初始掷骰中四个骰子的总和。
请注意,它们是一个名为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))
,
您需要计算for循环内的骰子总和。
在您的示例中,总和始终等于在对random.randint
的前4次调用中生成的随机数总和,但是您应该每次都重新计算总和。
此外,在有for sum >= 21
的行中,应将for
替换为if
。 for
用于重复,if
用于条件执行。
我解决了这个问题。你可以试试吗
import random
n = 0
for i in range(1000):
dice1 = random.randint(1,6)
sum = dice1 + dice2 + dice3 + dice4
if sum >= 21:
n = n + 1
print("You got 21 or higher","times.")
,
您不需要定义骰子,每个name; timestamp
math; 11/14/19 14:11
math; 11/14/19 14:11
math; 11/15/19 15:49
physics; 11/15/19 12:55
physics; 11/15/19 12:57
physics; 11/15/19 16:51
都是骰子本身。
random.randint(1,6)
这是一种Python方法:
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)
if sum >= 21:
n = n+1
print("You got 21 or higher",str(n),"times.")
我要做的就是每次骰子为dice_sum = [int((x/x)) for x in range(1,1001) if random.randint(1,6) >= 21]
print("You got 21 or higher",str(sum(dice_sum)),"times.")
时获得索引,然后将其除以相同的索引,以便它返回1到列表中,然后得到列表的总和,这就是将1多次添加到列表中,这就是骰子是>= 21
的次数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。