-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 のヒストグラム メソッドを使用できます。

または、必要なビン (ここでは 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 に答える