Python - 创建 2 个骰子以公平地掷骰子并将它们加在一起



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

"然后编写另一个函数来模拟掷两个公平的骰子。简单的方法是调用你刚刚编写的函数两次,然后把你得到的数字相加。这应该返回一个介于 2 和 12 之间的数字。

我已经第二次添加了掷骰子,但我的问题是如何将两次掷骰子的总和相加?这是我的代码。

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
        if roll() == "2":
            twoCount +=1
    print ("In", n,"rolls of a pair of dice, there were",twoCount,"twos.")
rollManyCountTwo(6000)

你根本不应该处理字符串,这可以完全使用 int 值来完成

from random import randint
def roll():
    return randint(1,6)
def roll_twice():
    total = 0
    for turn in range(2):
        total += roll()
    return total

例如

>>> roll_twice()
10
>>> roll_twice()
7
>>> roll_twice()
8

对于应该计算滚动2数量的函数,您可以再次进行整数比较

def rollManyCountTwo(n):
    twos = 0
    for turn in range(n):
        if roll() == 2:
            twos += 1
    print('In {} rolls of a pair of dice there were {} twos'.format(n, twos))
    return twos
>>> rollManyCountTwo(600)
In 600 rolls of a pair of dice there were 85 twos
85
from random import randint
def roll():
    return randint(1,6)
def rollManyCountTwo(n):
    twoCount = 0
    for _n in xrange(n*2):
        if roll() == 2:
            twoCount += 1
    print "In {n} rolls of a pair of dice, there were {cnt} twos.".format(n=n, cnt=twoCount)
由于您掷两个骰子 n 次并

计算每掷出两个骰子,只需循环n*2并检查骰子结果是否为两个。

最新更新