繁体   English   中英

在Python中模拟滚动2个骰子

[英]simulating rolling 2 dice in Python

我被要求模拟滚动两个带有1-6边的公平骰子。 因此,可能的结果是2-12。

我的代码如下:

def dice(n):
    x=random.randint(1,6)
    y=random.randint(1,6)
    for i in range(n):
        z=x+y
    return z

我的问题是,这仅返回掷骰子1次的结果,因此结果始终为2-12。 我希望它返回掷骰子(n)次的总和。

有人对我有什么建议吗?

在循环中掷骰子:

def dice(n):
    total = 0
    for i in range(n):
        total += random.randint(1, 6)
    return total

在对整数求和时total = total + random.randint(1, 6) +=扩充赋值运算符基本上可以归结为与total = total + random.randint(1, 6) (比这稍微复杂一点,但这仅对诸如列表之类的可变对象很重要)。

您甚至可以使用生成器表达式sum()函数

def dice(n):
    return sum(random.randint(1, 6) for _ in range(n))

基本上,这与第一个示例中的for循环相同。 循环n次,将1到6之间(包括1和6)的许多随机数相加。

如果不是要滚动n次,您需要产生2次掷骰子的n结果,您仍然需要滚动循环,并且需要将结果添加到列表中:

def dice(n):
    rolls = []
    for i in range(n):
        two_dice = random.randint(1, 6) + random.randint(1, 6)
        rolls.append(two_dice)
    return rolls

也可以使用列表理解更紧凑地写出:

def dice(n):
    return [random.randint(1, 6) + random.randint(1, 6) for _ in range(n)]

您还可以从生成的总和列表中使用random.choice() 这些将自动正确加权; 这基本上可以预先计算出36个可能的骰子值(11个唯一),每个值具有相等的概率:

from itertools import product

two_dice_sums = [a + b for a, b in product(range(1, 7), repeat=2)]

def dice(n):
    return [random.choice(two_dice_sums) for _ in range(n)]

无论哪种方式,您都将得到一个包含n结果的列表:

>>> dice(5)
[10, 11, 6, 11, 4]
>>> dice(10)
[3, 7, 10, 3, 6, 6, 6, 11, 9, 3]

您可以将列表传递给print()函数,以将它们打印在一行或一行上:

>>> print(*dice(5))
3 7 8 6 4
>>> print(*dice(5), sep='\n')
7
8
7
8
6

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM