【问题标题】:Distribution of dice rolls [duplicate]骰子的分布[重复]
【发布时间】:2016-01-31 23:39:37
【问题描述】:
from random import randrange

def roll2dice() -> int:
    roll2 = []
    for i in range(50):
        sum = randrange(1,7) + randrange(1,7)
        roll2.append(sum)
    return roll2

上述函数用于生成两个骰子的随机滚动和。

def distribution (n: int):
    result = []
    for x in range(2,13):
        result.append(roll2dice())
    for x in range(2,13):
        dice = result.count(x)
        num_of_appearances = result.count(x)
        percentage = (result.count(x) / int(n)) * 100
        bar = result.count(x)*'*'
    print("{0:2}:{1:8}({2:4.1f}%)  {3.5}".format(dice, num_of_appearances, percentage, bar))

然后我使用 roll2dice 创建了一个分布函数,其中

distribution(200)

应该让步:

 2:     7 ( 3.5%)  *******
 3:    14 ( 7.0%)  **************
 4:    15 ( 7.5%)  ***************
 5:    19 ( 9.5%)  *******************
 6:    24 (12.0%)  ************************
 7:    35 (17.5%)  ***********************************
 8:    24 (12.0%)  ************************
 9:    28 (14.0%)  ****************************
10:    18 ( 9.0%)  ******************
11:     9 ( 4.5%)  *********
12:     7 ( 3.5%)  *******

但是,错误提示:

Traceback (most recent call last):
  File "C:/Python34/lab6.py", line 23, in <module>
distribution_of_rolls(200)
  File "C:/Python34/lab6.py", line 21, in distribution_of_rolls
    print("{:2d}:{1:8d}({2:4.1f}%)  {3.5s}".format(dice_num, num_of_appearance, percentage, stars))
ValueError: cannot switch from automatic field numbering to manual field specification

【问题讨论】:

  • 哪个构造导致错误?请添加完整的未更改的错误消息。
  • 我已经编辑了帖子
  • roll2dice 如果将滚动数作为参数 n 会更有用,并且可以在一行中定义 return [randrange(1,7)+randrange(1,7) for i in range(n)]

标签: python python-3.x random probability


【解决方案1】:

前3个字段是{n_field:format},最后一个字段是{3.5},没有字段号。

这是您想要做的(我认为)的工作版本:

from random import randrange

def distribution (n: int):
    result = []
    for x in range(n):
        sum = randrange(1,7) + randrange(1,7)
        result.append(sum)
    for dice in range(2,13):
        num_of_appearances = result.count(dice)
        percentage = (num_of_appearances / n) * 100
        bar = int(percentage) * '*'
        print("{0:2}:{1:8} ({2:4.1f}%)  {3}".format(dice, num_of_appearances, percentage, bar))

或者,使用列表理解:

from random import randrange

def distribution (n: int):
    for dice in [randrange(1,7) + randrange(1,7) for _ in range(n)]:
        num_of_appearances = result.count(dice)
        percentage = (num_of_appearances / n) * 100
        bar = int(percentage) * '*'
        print("{0:2}:{1:8} ({2:4.1f}%)  {3}".format(dice, num_of_appearances, percentage, bar))

【讨论】:

  • 既然我应该在分发函数中使用roll2dice函数,我应该在哪里合并它?我尝试过“for x in range(n): result.append(roll2dice()),但这没有用。
  • append 将向列表中添加一个列表,您最终会得到一个列表列表。您可以使用extend,它将列表的元素添加到列表中。这有点违背了拥有一个功能的目的,这就是我删除它的原因。也许我不明白你为什么要使用它。
猜你喜欢
  • 1970-01-01
  • 2020-10-06
  • 1970-01-01
  • 2021-12-15
  • 2011-02-10
  • 2017-08-28
  • 1970-01-01
  • 2012-07-07
相关资源
最近更新 更多