Last active
August 1, 2018 05:47
-
-
Save johnta0/8a7715ea2fc097b9df068eca9603bdf7 to your computer and use it in GitHub Desktop.
Monty Hall問題のシミュレーションプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
# | |
# @author Johnta | |
# | |
""" | |
モンティ・ホール問題を数値シミュレーションするプログラム | |
モンティ・ホール問題について => http://mathtrain.jp/monty | |
使い方:試行回数を入力するだけ | |
環境:Python3 | |
""" | |
import random | |
class MontyHall: | |
def __init__(self, trials): | |
self.trials = trials | |
# ドアを変更しない場合の処理を行うメソッド | |
def do_without_change(self): | |
# 車があるドアをランダムに選択 | |
where_is_car = random.randint(1, 3) | |
# 挑戦者の選択するドアもランダムに選択 | |
where_you_choose = random.randint(1,3) | |
if where_is_car == where_you_choose: | |
return 1 | |
else: | |
return 0 | |
# ドアを変更する場合の処理を行うメソッド | |
def do_change(self): | |
# 車があるドアをランダムに選択 | |
where_is_car = random.randint(1, 3) | |
# 挑戦者の選択するドアもランダムに選択 | |
where_you_choose = random.randint(1,3) | |
# Montyが、挑戦者が選んだドア以外のうち、ハズレの方を選ぶ | |
while True: | |
where_monty_choose = random.randint(1, 3) | |
if where_monty_choose != where_is_car and where_monty_choose != where_you_choose: | |
break | |
# Montyが選ばなかった方のドアに変更する処理 | |
while True: | |
where_you_choose2 = random.randint(1, 3) | |
if where_you_choose2 != where_monty_choose and where_you_choose2 != where_you_choose: | |
break | |
# 当たったかの判定 | |
if where_is_car == where_you_choose2: | |
return 1 | |
else: | |
return 0 | |
# 実際に試行する。当たった回数もカウント。 | |
def try_without_change(self): | |
winCount = 0 | |
for i in range(1, self.trials): | |
winCount += self.do_without_change() | |
return winCount | |
def try_with_change(self): | |
winCount = 0 | |
for i in range(1, self.trials): | |
winCount += self.do_change() | |
return winCount | |
if __name__ == '__main__': | |
trials = int(input("試行回数︰")) | |
challenge = MontyHall(trials) | |
try_with_change = challenge.try_with_change() | |
try_without_change = challenge.try_without_change() | |
print("変えなかった場合:") | |
print("当たった回数=> " + str(try_without_change)) | |
print("当たった確率=> " + str(try_without_change/trials*100) + " %") | |
print('--------------------------------------') | |
print("変えた場合:") | |
print("当たった回数=> " + str(try_with_change)) | |
print("当たった確率=> " + str(try_with_change/trials*100) + " %") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment