fork download
  1. import random
  2.  
  3. def monty_hall_simulation(trials):
  4. stay_wins, switch_wins = 0, 0
  5. for _ in range(trials):
  6. # 随机分配奖品(0:山羊,1:车)
  7. doors = [0, 0, 1]
  8. random.shuffle(doors)
  9.  
  10. # 参赛者初始选择
  11. choice = random.randint(0, 2)
  12.  
  13. # 主持人排除一个山羊门
  14. remain_doors = [i for i in range(3) if i != choice and doors[i] != 1]
  15. host_open = random.choice(remain_doors)
  16.  
  17. # 换门策略:选择剩下的未开启门
  18. switch_choice = [i for i in range(3) if i != choice and i != host_open][0]
  19.  
  20. # 统计结果
  21. if doors[choice] == 1:
  22. stay_wins += 1
  23. if doors[switch_choice] == 1:
  24. switch_wins += 1
  25.  
  26. return stay_wins/trials, switch_wins/trials
  27.  
  28. # 模拟10,000次实验
  29. stay_prob, switch_prob = monty_hall_simulation(1000000)
  30. print(f"不换门胜率: {stay_prob:.2%},换门胜率: {switch_prob:.2%}")
Success #stdin #stdout 4.01s 14220KB
stdin
Standard input is empty
stdout
不换门胜率: 33.38%,换门胜率: 66.62%