编写一个函数来对两个随机骰子滚动n次的结果求和

时间:2016-09-05 00:18:25

标签: python sage dice

写一个函数DiceRoll(n),它输入一个整数n并产生n个随机数 在1到6之间测试你的程序n = 12.

我得到了这个:

import random

def DiceRoll(n):
    x=[random.randint(1,6) for _ in range(n)]
    return x

然后,

编写一个函数TwoDiceRoll(n),它使用你的函数DiceRoll来求和的结果 滚动两个随机骰子n次。测试你的程序n = 12。

我不知道如何获取DiceRoll功能以获得总和。有人能够帮助我吗?

2 个答案:

答案 0 :(得分:-1)

<强>代码:

import random

def TwoDiceRoll(n):
    d1=DiceRoll(n)
    d2=DiceRoll(n)
    dsum=[i+j for i,j in zip(d1, d2)]

    return d1,d2,dsum

def DiceRoll(n):
    x=[random.randint(1,6) for _ in range(n)]
    return x

x=DiceRoll(12)
print x

d1,d2,dsum=TwoDiceRoll(12)
print d1, "\n", d2, "\n", dsum

示例输出:

# It will be different everytime because of random function.
[3, 2, 3, 6, 4, 3, 5, 4, 4, 4, 2, 4]
[1, 4, 1, 2, 4, 1, 6, 5, 2, 6, 6, 5]
[4, 2, 3, 1, 6, 3, 1, 5, 5, 2, 6, 3]
[5, 6, 4, 3, 10, 4, 7, 10, 7, 8, 12, 8]

答案 1 :(得分:-2)

不确定为什么要总结它们但是你走了!我相信你有能力将它包装在一个函数中!

import random

def DiceRoll(n):
    x=[random.randint(1,6) for _ in range(n)]
    return x

d1 = DiceRoll(12)
d2 = DiceRoll(12)
print sum(d1+d2)