台北來的土包子
 
Python -The Monty Hall Problem

Python -The Monty Hall Problem

蒙提霍爾問題
這是一個有趣的數學機率問題,源自於美國的電視節目 Let’s Make a Deal,遊戲有三扇門,其中一扇門後藏著汽車,另二扇門則是山羊,參賽者先從三扇門中選擇一扇,之後主持人會將再移除另兩扇門的其中一扇,而該扇門後一定的山羊。此時參賽者可以有再一次的選擇權,看是要保留第一次選擇的門,還是選擇主持人留下的另一扇門。
如果你是參賽者你會換嗎?在寫這個程式之前,我的選擇是不換,但測試後的結果,還是換比較好。

#The Monty Hall Problem
#https://www.george.tw/2020/03/05/python-the-monty-hall-problem/
import random
guessCount=0
rightCount = 0
while True:
    door=random.randint(1,3)           # Generates a random integer range of 1-3, this is for a prize
    firstChoice=int(input("Choose a door from 1-3 , to exit the program, press 4 :"))  # Let user choose a door
    if (firstChoice==4): break         #  if user press 4 then exit while loop
    guessCount =guessCount +1          # Count the number of guesses
    doorList=[1,2,3]                   # This array are the number of the doors
    doorList.pop(door-1)               # We removed the door of the prize's in the array
    if (firstChoice != door):          # If user's choice is not equal to prize 
        newList=[firstChoice,door]     # We put user's choice and the prize in to the new array
    else:    
        second=random.randint(1,2)     # If user's choice is equal to prize, we generates a random integer range of 1-2, and removed one of the doors
        newList=[doorList[second-1], door]     
    newList.sort()                    
    secondChoice=int(input("Choose another door from {:d},{:d}:".format(newList[0],newList[1])))   # Let user choose new doors 

    if (secondChoice==door):          # The result of user choice 
        print ("You win, the door is {:d}".format(door))
        rightCount = rightCount+ 1    #  The count of correct choice
    else:
        print ("You loss, the door is {:d}".format(door))

print("{:d} guesses in total".format(guessCount))
print("{:d} correct guesses".format(rightCount))
print ("The chance of guessing correctly is {:.3f}".format(rightCount/guessCount))   # Result


door=random.randint(1,3) 利用亂數產生一扇門,這扇門代表獎品
firstChoice 使用者第一次猜測的門(1-3) , 4 離開程式
guessCount 計算使用者猜測的次數
doorList 3 扇門,編號 1 , 2 , 3
doorList.pop(door-1) 先把是獎品編號的門從陣列中移出
if .. else … 這裡要產生新的選擇:
如果參賽者的猜測中沒有獎品,
我們把使用者的選擇和有獎品的門放入新的陣列中
如果參賽者選中門
我們先隨機產生一個數字,
留下一扇門並與 參賽者選中的門產生一個新的陣列
newList.sort() 陣列排序
判斷結果,並計算機率

原始碼: GitHub

大致上換的得獎機率會在 66.6 % 上下
…待續

發表迴響