【发布时间】: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