Monty Hall模拟器有错误的结果

时间:2017-05-15 19:57:14

标签: python python-3.x math

我想做一些看似简单的事情,同时通过代码证明Monty Hall,遗憾的是我得到的并不是问题的证明,而是完全相反。无论我是否改变,我在10000次模拟中获胜的可能性约为33%。你能检查代码,看看它有什么问题吗?请记住,我是一个web-dev,所以我的Python技能不是很好,而且代码可能看起来不太棒(例如,我创建了一个只有变量才能正常运行的removable_doors列表)。干杯!

import random
av_doors = [1, 2, 3]
door_v = [1, 2, 3]
removable_doors = [1, 2, 3]
score = 0
loses = 0

door = int(input("Choose your door (1-3)"))
pick = int(door)-1

dec = input("Stay or switch? (0/1)")

n = 0
while n < 10000:
    removable_doors = [1, 2, 3]
    av_doors = [1, 2, 3]
    val = random.randint(1,3)
    if val == 1:
        door_v[0] = 1
        door_v[1] = 0
        door_v[2] = 0
        removable_doors.remove(1)
    elif val == 2:
        door_v[0] = 0
        door_v[1] = 1
        door_v[2] = 0
        removable_doors.remove(2)
    elif val == 3:
        door_v[0] = 0
        door_v[1] = 0
        door_v[2] = 1
        removable_doors.remove(3)

    try:
        removable_doors.remove(int(door))
    except:
        pass

    av_doors.remove(door)

    if len(removable_doors) == 2:
        rand_door = random.randint(0,1)
        if rand_door == 0:
            del av_doors[0]
        elif rand_door ==1:
            del av_doors[1]
    else:
        del av_doors[0]

    if dec == "1":   
        door = av_doors[0]
    else:
        pass

    pick = door-1
    if door_v[pick] == 1:
        score+=1
    else:
        loses+=1

    n+=1

print(score)
print(loses)

1 个答案:

答案 0 :(得分:2)

你的主人有时会把车门挡在车门后面...这是一个有效的解决方案,而且(我认为)写得更好,同时保留你的结构(在python3但不应该引起麻烦):< / p>

import random

win = 0
lose = 0

switch = int(input("Stay or switch? (0-stay/1-switch):")) == 1

n = 0
while n < 10000:
    # Init
    door_values = [0, 0, 0]
    removable_doors = [0, 1, 2]
    available_doors = [0, 1, 2]

    # Placing the reward somewhere
    car_place = random.randint(0, 2)
    door_values[car_place] = 1
    removable_doors.remove(car_place)

    # Choose a door
    door_chosen = random.randint(0, 2)
    available_doors.remove(door_chosen)
    if door_chosen != car_place:
        removable_doors.remove(door_chosen)

    # Host removes a door that does not have the car and has not been chosen by the player

    door_removed_by_host = removable_doors[random.randint(0, len(removable_doors)-1)]
    available_doors.remove(door_removed_by_host)

    # Switch if specified
    if switch:
        assert(len(available_doors) == 1)
        door_chosen = available_doors[0]

    # Check the result
    if car_place == door_chosen:
        win += 1
    else:
        lose += 1

    n+=1

print('win=%s'%str(win))
print('lose=%s'%str(lose))
print('ratio=%s'%str(win/(win+lose)))

它为0.3332 switch=False0.6738 switch=True给了我public class Mother{ public foo() throws Exception{ system.out.println("I am mother"); } } public class Daughter extends Mother{ @Override public foo() throws Exception{ throws new Exception("I am a teenager !!"); } } ,我想这确实证实了Monty Hall的解决方案:)