開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 13.(Case Study: Data Structure Selection)のExercises 13-5.(No. 2955)を取り組んでみる。
Exercises 13-5.(No. 2955)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
def histogram(s):
d = {}
for c in s:
d[c] = d.get(c, 0) + 1
return d
def choose_from_hist(hist):
keys = [key for key in hist.keys() for _ in range(hist[key])]
return random.choice(keys)
if __name__ == '__main__':
t = 'aab'
hist = histogram(t)
count_a = 0
count_b = 0
n = 10000
for _ in range(n):
ch = choose_from_hist(hist)
if ch == 'a':
count_a += 1
else:
count_b += 1
print('probability a: {0}, b: {1}'.format(count_a / n, count_b / n))
入出力結果(Terminal, IPython)
$ ./sample5.py probability a: 0.6713, b: 0.3287 $
0 コメント:
コメントを投稿