コンソールで確率分布表示[7/13/2012] Challenge #76 [intermediate] (Probability graph) : dailyprogrammer

問題

Challenge #76 (Probability graph) : dailyprogrammer
low から high までの出力を持つ関数 f を tests 回実行した時の確率分布を出力する。

def two_dice():
    return random.randint(1, 6) + random.randint(1, 6)

def graph(f, low, high, tests):
    pass    # ここを実装

graph(f, 2, 12, 10000)
"""
  2: ##
  3: #####
  4: #######
  5: ###########
  6: #############
  7: #################
  8: #############
  9: ###########
 10: ########
 11: #####
 12: ##
"""

回答

Python 2.6

import random
def two_dice():
    return random.randint(1, 6) + random.randint(1, 6)

def graph(f, low, high, tests):
    freq = [0 for _ in range(low, high+1)]

    for i in range(tests):
        freq[f()-low] += 1

    for i in range(high+1-low):
        print "%02d:" % (i+low), "#" * (freq[i] * 100 / tests)

f = two_dice
graph(f, 2, 12, 10000)

"""
02: ##
03: #####
04: ########
05: ##########
06: #############
07: #################
08: #############
09: ###########
10: ########
11: #####
12: ##
"""

ちょっとカンニング…。難易度はeasy, intermediate, hardの3段階あるけど回によっても難しさにムラがあるみたい。