Skip to content

Instantly share code, notes, and snippets.

@AtsushiSakai
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AtsushiSakai/9718853 to your computer and use it in GitHub Desktop.
Save AtsushiSakai/9718853 to your computer and use it in GitHub Desktop.
モンティ・ホール問題をシミュレーションするPythonプログラム
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @brief モンティ・ホールゲームを指定した回数実施し、
# 勝った回数を比較するシミュレーションソフト
#
# @Author Atsushi Sakai
import random #乱数発生用
def Main():
print "Monty Hall Simulation Start!!"
GAME_COUNT=1000 #ゲームの回数
#扉を変更しない場合のゲームを実施
NCWinCount=DoGames("NoChange",GAME_COUNT)
print "Win Count (No Change):"
print NCWinCount
#扉を変更する場合のゲームを実施
WCWinCount=DoGames("WithChange",GAME_COUNT)
print "Win Count (With Change):"
print WCWinCount
def DoGames(MODE,GCOUNT):
winCount=0 #勝った回数
#指定した回数ゲームをする
for ig in range(GCOUNT):
if(MODE=="NoChange"):
winCount+=DoOneGameNoChange()
elif(MODE=="WithChange"):
winCount+=DoOneGameWithChange()
return winCount
def DoOneGameWithChange():
#宝の場所をランダムに選ぶ
treasure=random.randint(1, 3)
#プレイヤーの最初の扉を選ぶ
firstChoise=random.randint(1, 3)
#司会者がハズレの扉で、プレイヤーが選んでいないものを選ぶ
while(1):
montyChoise=random.randint(1, 3)
if (montyChoise!=treasure)&(montyChoise!=firstChoise):
break;
#司会者が選ばなかった方の扉に変更する
while(1):
secondChoise=random.randint(1, 3)
if (secondChoise!=montyChoise)&(secondChoise!=firstChoise):
break;
if secondChoise==treasure:
return 1 #あたり
else:
return 0 #はずれ
def DoOneGameNoChange():
#宝の場所をランダムに選ぶ
treasure=random.randint(1, 3)
#プレイヤーの最初の扉を選ぶ
firstChoise=random.randint(1, 3)
if firstChoise==treasure:
return 1 #あたり
else:
return 0 #はずれ
if __name__ == "__main__":
Main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment