使用python完全模拟三门问题

 

使用python完全模拟三门问题_第1张图片

 使用python完全模拟三门问题_第2张图片

使用python完全模拟三门问题_第3张图片

import random
import time
def getRandomIntNum(minNum=0,maxNum=2):
    num=random.randint(minNum,maxNum)
    return num

def initDoors():
    doors=[False]*3
    randomNum=getRandomIntNum()
    carDoorIndex=randomNum
    doors[carDoorIndex]=True
    return doors

def chooseDoor():
    return getRandomIntNum()

def checkOtherDoor_random(doors,choseIndex):
    otherDoorsIndices=[]
    for index in range(len(doors)):
        if index !=choseIndex:
            otherDoorsIndices.append(index)
    randomNum=getRandomIntNum(0,1)
    checkIndex=otherDoorsIndices[randomNum]
    checkResult=doors[checkIndex]
    return (checkIndex,checkResult)

def checkOtherDoor_special(doors,choseIndex):
    for index in range(len(doors)):
        if index!=choseIndex:
            if(doors[index]==False):
                return index,False
def getChangedResult(doors,choseIndex,checkIndex):
    for index in range(len(doors)):
        if index != choseIndex and index != checkIndex:
            if doors[index] == True:
                return 'win'
            else:
                return 'lose'

def getKeepResult(doors,choseIndex):
    if doors[choseIndex] == True:
        return 'win'
    else:
        return 'lose'

# playerStrategy='change' or playerStrategy='keep'
# gameStrategy='random' or gameStrategy='special'
def playThreeDoorsGame(gameStrategy='special',playerStrategy='change'):
    doors=initDoors()
    choseIndex=chooseDoor()
    if gameStrategy=='special':
        checkOtherDoor=checkOtherDoor_special
    elif gameStrategy=='random':
        checkOtherDoor=checkOtherDoor_random
    checkIndex,checkResult=checkOtherDoor(doors,choseIndex)

    if checkResult==True:
        return 'Game over'
    if playerStrategy=='change':
        gameResult=getChangedResult(doors,choseIndex,checkIndex)
        return gameResult
    if playerStrategy=='keep':
        gameResult=getKeepResult(doors,choseIndex)
        return gameResult


if __name__=="__main__":
    random.seed(time.time())
    countMap={}
    countMap['win']=0
    countMap['lose']=0
    countMap['Game over']=0

    #在裁判排除一个门之后玩家是否变更选择
    playerStrategy='change'# playerStrategy='change' or playerStrategy='keep'

    # special就是三门问题中裁判的策略,会帮玩家排除掉错误的门
    # random是随机排除一个
    gameStrategy='special'# gameStrategy='random' or gameStrategy='special'

    playCounts=10000

    for i in range(playCounts):
        res=playThreeDoorsGame(gameStrategy,playerStrategy)
        countMap[res]+=1
    print(countMap)

  看到张大仙使用高深的三门理论玩游戏,顿时心生敬佩,打算看看这个三门问题到底怎么回事。先是拿扑克进行了大量的10组实验,迷迷糊糊中好像发现了事情的神奇。于是又编写了模拟程序,看看事实的真相究竟如何。结果证明张大仙只是运气好,这根本不是三门问题。哎,真相就是这么的乏味。。。。。。

 

 

你可能感兴趣的:(python)