-1

这些是用于掷骰子的函数。

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

帮助表示赞赏。谢谢

4

2 回答 2

0

如果您对图形输出没问题,您可以使用matplotlib 中的 histogram 方法

或者你可以手动创建你需要的箱子,这里是整数 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
于 2012-11-07T07:16:56.843 回答
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)
于 2012-11-07T06:51:49.827 回答