티스토리 뷰
몬티홀 문제를 100만번 반복해서 실행해 보는 코드이다.
매번 게임판이 달라지며, 모든 선택은 무작위로 일어난다고 가정 (Python의 random 모듈에 의존).
import random
def generate_doors():
d = [0, 0, 0]
ans_door = random.randint(0, 2)
d[ans_door] = 1
return d, ans_door
def select_door():
return random.randint(0, 2)
def open_door(d, selected):
empty_doors = []
for i, door in enumerate(d):
if door != 1 and i != selected:
empty_doors.append( i )
# end of if
# end of for
return random.choice( empty_doors )
def get_choices(d, opened):
remained_doors = []
for i, door in enumerate(d):
if i != opened:
remained_doors.append( i )
# end of if
# end of for
return remained_doors
num_suc_rand = 0 # The number of successes : random selection
num_suc_change = 0 # The number of successes : changing the answer
num_suc_stay = 0 # The number of successes : staying at the original answer
num_trials = 1000000
for j in range(0, num_trials):
doors = []
doors, ans_door = generate_doors()
#print "doors: ", doors
#print "ans: ", ans_door
selected_door = select_door()
#print "selected: ", selected_door
opened_door = open_door( doors, selected_door )
#print "opened: ", opened_door
remained_doors = get_choices( doors, opened_door )
#print "remained: ", remained_doors
# Stay the first answer
if selected_door == ans_door:
num_suc_stay += 1
# Random selection
rand_sel = random.choice( remained_doors )
#print "rand_sel: ", rand_sel
if rand_sel == ans_door:
num_suc_rand += 1
#print "rand_sel: success"
# Change selection
other_choices = []
for e in remained_doors:
if e != selected_door:
other_choices.append( e )
# end of for
change_sel = random.choice( other_choices )
#print "change_sel: ", change_sel
if change_sel == ans_door:
num_suc_change += 1
#print "change_sel: success"
# end of for
"<Success rates>"
print "Staying at the original answer: %f"%( float(num_suc_stay)/num_trials )
print "Changing the answer: %f"%( float(num_suc_change)/num_trials )
print "Random selection: %f"%( float(num_suc_rand)/num_trials )
실행 결과의 예는 다음과 같다.
Staying at the original answer: 0.334354
Changing the answer: 0.665646
Random selection: 0.500010
'Python > 요리 방법' 카테고리의 다른 글
Cython 간단한 예제 (0) | 2015.02.28 |
---|---|
OpenBLAS를 이용하여 numpy와 scipy 설치 (0) | 2014.06.10 |
An algorithm of Permutation in DNA Computing (0) | 2011.12.23 |
Eclipse + Python (0) | 2011.09.22 |
CentOS 5.6 에서 Python2.6 + PyQt4 + matplotlib 설치하기 (0) | 2011.08.31 |
- Total
- Today
- Yesterday
- GSX 1200 pro
- how to solve it
- 볼륨 낮춤
- TCGA
- volume dial
- QPrinter.Letter
- Python
- dll
- MSVC++
- 설치
- tensorflow
- 이상한 문자
- C++
- QPrinter.A4
- Accelerated C++
- ctypes
- matrix multiplication
- cython
- CanDrA
- TensorBoard
- structure
- QT
- destructor
- PyQt
- pandas
- GSX 1000 pro
- armadillo c++
- 볼륨 조절
- Visual C++
- Item 9
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |