骰子分布

Distribution of dice rolls

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

前 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))