Python - 创建2个骰子公平滚动并将它们一起添加?

时间:2015-06-19 11:22:59

标签: python dice

因此,我必须制作能够公平地掷骰子的代码并计算我得到了多少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)

2 个答案:

答案 0 :(得分:4)

你根本不需要处理字符串,这可以完全使用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

答案 1 :(得分:1)

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并检查骰子结果是否为2。