这些是用来掷骰子的功能。
def roll() -> int:
''' Return a roll of two dice, 2-12
'''
die1 = randint(1, 6)
die2 = randint(1, 6)
return die1 + die2
def roll_dice(n:int):
'''list the results of rolls'''
for i in range(n):
print(roll())
现在我需要帮助来创建一个函数来创建滚动数字的统计信息列表。
例如:打印完所述功能后,应根据我的实验打印出这样的东西:
Distribution of dice rolls
2: 55 ( 2.8%) **
3: 129 ( 6.5%) ******
4: 162 ( 8.1%) ********
5: 215 (10.8%) **********
6: 279 (14.0%) *************
7: 341 (17.1%) *****************
8: 271 (13.6%) *************
9: 210 (10.5%) **********
10: 168 ( 8.4%) ********
11: 112 ( 5.6%) *****
12: 58 ( 2.9%) **
-----------------
2000 rolls
帮助表示赞赏。感谢
答案 0 :(得分:0)
from collections import defaultdict
def roll_dice(n):
'''list the results of rolls'''
d = defaultdict(int)
for i in range(n):
res = roll()
d[res] += 1 #accumulate results
print(res)
print ("RESULTS")
#sort and print results. Since there's only 11 items,
# There is no sense using `iteritems()` here. We'd
# just have to change it for py3k...
for key,value in sorted(d.items()):
percent = float(value)/n*100
#print results. Use explicit field widths to make sure the "bargraph" is aligned.
print ('{0:2d}:{1:4d}\t({2:6f}%)\t{3}'.format(key,value,percent,int(percent)*'*'))
roll_dice(2000)
答案 1 :(得分:0)
如果您对图形输出没问题,可以使用histogram method from matplotlib。
或者你可以手动创建你需要的箱子,这里是整数2到12,并简单地计算每个箱子里有多少卷筒。通过滚动次数标准化以获得百分比并为每1%添加一颗星(显然向下舍入)。
经过一些修改后,产生以下代码(python 2.X):
import random
import math
def roll():
''' Return a roll of two dice, 2-12
'''
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
return die1 + die2
def roll_dice(npts):
'''list the results of rolls'''
bins = dict([(n,0) for n in xrange(2,13,1)])
for n in xrange(npts):
idx = roll()
print idx
bins[idx] = bins[idx] + 1
for n in xrange(2,13,1):
pct = bins[n]/float(npts) * 100.0
pct_star = ''
for i in xrange(int(math.floor(pct))):
pct_star = pct_star + '*'
str = "{0:.1f}%".format(pct).rjust(5,' ')
print "{0:2d}: {1:5d} ({2:s}) {3:s}".format(n,bins[n],str,pct_star)
print "------------------"
print "{0:10d} rolls".format(npts)
if __name__ == "__main__":
npts = 20000
roll_dice(2000)
输出
2: 569 ( 2.8%) **
3: 1131 ( 5.7%) *****
4: 1770 ( 8.8%) ********
5: 2229 (11.1%) ***********
6: 2778 (13.9%) *************
7: 3307 (16.5%) ****************
8: 2703 (13.5%) *************
9: 2231 (11.2%) ***********
10: 1633 ( 8.2%) ********
11: 1128 ( 5.6%) *****
12: 598 ( 3.0%) **
------------------
20000 rolls