Coin-throwing

Python 怎麼擲硬幣

PTT 的 Python 板有人問說:「Python 怎麼擲硬幣」。我剛好有參與討論,覺得有趣,整理於後。

一開始某網友給的解答:

# No Pythonic by timerover:
import random
 
N = 100
count = 0
 
for i in range(N):
    if random.randint(0, 1) == 1:
        count += 1
        print 'H'
    else:
        print 'T'
 
print 'H:', count
print 'T:', N - count

另一個網友提出 Pythonic 的版本:

# Pythontic by ibmibm:
import random
 
N = 100
hist = [random.choice(('H', 'T')) for i in range(N)]
for e in hist:
    print e
print 'H:', hist.count('H')
print 'T:', hist.count('T')

最後我想到一個又 Pythonic 又省空間的寫法:

# Pythonic with space saving by ykjiang:
import random
 
N = 100
hist = (random.choice(('H', 'T')) for i in xrange(N))
m = {'H':0, 'T':0}
for e in hist:
    m[e] += 1
    print e
print 'H: ', m['H']
print 'T: ', m['T']

另一個是男生的機率

今天(2010/01/13)在科技版看到一個機率問題,很驚訝竟然那麼多人自作聰明的給了複雜卻錯誤的解答。

為了增加說服力,這裡就照慣例,用爬說語解答好了 :)

題目

「小明過年期間去拜訪許久沒見面的同學,聽說同學已經生了兩個小孩,進門後小明看到朋友其中一個小孩是男生,請問,另一個是男生的機率為多少?」

用 Python 跑模擬

from numpy import arange, array, bincount
from numpy.random import random_integers
 
# Toss a coin with two thousand times
x = random_integers(0, 1, 2000)
print bincount(x)
 
# Count values after each 1s
idx = arange(len(x))[x==1] + 1
print bincount(x[idx[:-1]])
 
# Count values before each 1s
idx = arange(len(x))[x==1] - 1
print bincount(x[idx[1:]])

結果

In [96]: run rand
[ 974 1026]
[495 530]
[495 530]
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License