howmuch515 icon

monty_hall.py

howmuch515 | PRO | 10/23/18 12:27:01 AM UTC | 0 ⭐ | 279 👁️ | Never ⏰ | []
Python |

3 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env python3
#-*- coding: utf-8 -*-
import random, sys
 
#扉のクラス
class Door():
    def __init__(self, car, door):
        #車の有無
        self.car = car
        #ドアの開閉状態(閉=True, 開=False)
        self.door = door
 
    def openDoor(self):
        self.door = True
 
    #アクセサメソッド
    def getCar(self):
        return self.car
 
    def getDoor(self):
        return self.door
 
#3枚の扉のセット
class DoorS():
    def __init__(self):
        self.doorList = []
        #車のある扉の場所をランダムで決める
        self.carPosition = random.randint(0, 2)
        for i in range(3):
            if i==self.carPosition: self.doorList.append(Door(True, False))
            else: self.doorList.append(Door(False, False))
 
    #選択された扉に車があるかどうかの確認
    def confirm(self, userSelect):
        return self.getCarPosition() == userSelect
 
    #選択された扉ではない二枚の扉から車がない扉を一枚選んで扉を開く
    def openEmptyDoor(self, userSelect):
        for i in range(3):
            if i != userSelect and self.doorList[i].getCar() == False:
                self.doorList[i].openDoor()
                break
 
    #閉じられている扉の場所のリストを返す
    def getCloseDoor(self):
        return [i for i in range(3) if (self.doorList[i].getDoor() == False)]
 
    #車のある扉の場所を返す
    def getCarPosition(self):
        return self.carPosition
 
def main():
    #executionTimes回実行する
    executionTimes = int(sys.argv[1])
 
    #選択した扉を変更しない場合
    noChangeSelect = 0
    for i in range(executionTimes):
        doors = DoorS()
        #選択する扉の場所はランダムで決める
        userSelect = random.randint(0, 2)
        #ドアを一枚開ける
        doors.openEmptyDoor(userSelect)
        #最初に選択した扉に車があった場合、正解した回数をカウント
        if doors.confirm(userSelect) : noChangeSelect += 1
    print("最初の選択を変更しなかった場合の正解率は\t==> {0}%".format(noChangeSelect/executionTimes*100))
 
    #選択した扉を変更する場合
    ChangeSelect = 0
    for i in range(executionTimes):
        doors = DoorS()
        #選択する扉の場所はランダムで決める
        userSelect = random.randint(0, 2)
        #ドアを一枚開ける
        doors.openEmptyDoor(userSelect)
        #残った扉のうち、最初に選択した扉ではない方を選ぶ
        userSelect = doors.getCloseDoor()[1] if (doors.getCloseDoor()[0] == userSelect) else doors.getCloseDoor()[0]
        #最初に選択した扉に車があった場合、正解した回数をカウント
        if doors.confirm(userSelect) : ChangeSelect += 1
    print("最初の選択を変更した場合の正解率は\t\t==> {0}%".format(ChangeSelect/executionTimes*100))
 
if __name__ == '__main__':
    main()

Comments