티스토리 뷰

몬티홀 문제를 100만번 반복해서 실행해 보는 코드이다.

매번 게임판이 달라지며, 모든 선택은 무작위로 일어난다고 가정 (Python의 random 모듈에 의존).



import random


def generate_doors():

    d = [0, 0, 0]

    ans_door = random.randint(0, 2)

    d[ans_door] = 1

    return d, ans_door


def select_door():

    return random.randint(0, 2)



def open_door(d, selected):

    empty_doors = []

    for i, door in enumerate(d):

        if door != 1 and i != selected:

            empty_doors.append( i )

        # end of if

    # end of for        

    return random.choice( empty_doors )


def get_choices(d, opened):

    remained_doors = []

    for i, door in enumerate(d):

        if i != opened:

            remained_doors.append( i )

        # end of if

    # end of for


    return remained_doors


num_suc_rand = 0 # The number of successes : random selection

num_suc_change = 0 # The number of successes : changing the answer

num_suc_stay = 0 # The number of successes : staying at the original answer



num_trials = 1000000


for j in range(0, num_trials):


    doors = []


    doors, ans_door = generate_doors()

    #print "doors: ", doors

    #print "ans: ", ans_door


    selected_door = select_door()

    #print "selected: ", selected_door


    opened_door = open_door( doors, selected_door )

    #print "opened: ", opened_door


    remained_doors = get_choices( doors, opened_door )

    #print "remained: ", remained_doors




    # Stay the first answer

    if selected_door == ans_door:

        num_suc_stay += 1


    # Random selection

    rand_sel = random.choice( remained_doors )

    #print "rand_sel: ", rand_sel

    if rand_sel == ans_door:

        num_suc_rand += 1

        #print "rand_sel: success"


    # Change selection

    other_choices = []

    for e in remained_doors:

        if e != selected_door:

            other_choices.append( e )

    # end of for

    

    change_sel = random.choice( other_choices )

        

    #print "change_sel: ", change_sel

    if change_sel == ans_door:

        num_suc_change += 1

        #print "change_sel: success"


# end of for


"<Success rates>"

print "Staying at the original answer: %f"%( float(num_suc_stay)/num_trials )

print "Changing the answer: %f"%( float(num_suc_change)/num_trials )

print "Random selection: %f"%( float(num_suc_rand)/num_trials )



실행 결과의 예는 다음과 같다.


Staying at the original answer: 0.334354

Changing the answer: 0.665646

Random selection: 0.500010






댓글