【Python实验】三门问题 用蒙特卡洛法验证

image.png

现场有三扇关闭了的门,其中一扇的后面有辆跑车,而另外两扇门后面则各藏有一只山羊。
参赛者需要从中选择一扇门,如果参赛者选中后面有车的那扇门就可以赢得这辆跑车。
当参赛者选定了一扇门,但未去开启它的时候,节目主持人会开启剩下两扇门的其中一扇,露出其中一只山羊。
接下来参赛者会被问到:是否保持他的原来选择,还是转而选择剩下的那一道门?

import numpy as np


def plan_a(bingo, first_choice):
    ''' no change'''
    return bingo == first_choice


def plan_b(bingo, first_choice):
    '''change'''
    remainder = {'a','b','c'}
    not_show = {bingo, first_choice}
    show = remainder - not_show
    show = np.random.choice(list(show))
    second_choice = remainder - {show, first_choice}
    return bingo in second_choice


def run(plan = plan_a):
    gates = list('abc')
    bingo = np.random.choice(gates)
    first_choice = np.random.choice(gates)
    rslt = plan(bingo, first_choice)
    return rslt


def MC(runs = 10000, plan = plan_a):
    succeed = 0
    for i in range(runs):
        rslt = run(plan)
        if rslt:
            succeed += 1
    return succeed/runs

plan_a_rate = MC(runs = 100000, plan = plan_a)
plan_b_rate = MC(runs = 100000, plan = plan_b)
image.png

你可能感兴趣的:(【Python实验】三门问题 用蒙特卡洛法验证)