As requested, the version developed during lecture, not polished at all...


from random import choice

while True:
    try:
        nb_of_runs = int(input('How many times do you want '
                               'to run the simulation? '))
        break
    except ValueError:
        print('Input incorrect, try again!')

while True:        
    user_switches = input('Do you want to switch (yes/no)? ')
    if user_switches in {'Yes', 'No', 'yes', 'no', 'Y', 'N', 'y', 'n'}:
        break
    print('Input incorrect, try again!')
    
switches = user_switches[0] in 'Yy'
if switches:
    print('We run the simulation for a player who switches')
else:
    print('We run the simulation for a player who does not switch')
   
count_of_wins = 0
for _ in range(nb_of_runs):
    doors = ['A', 'B', 'C']
    winning_door = choice(doors)
    print('User does not know, but car is behind door {}'.format(winning_door))
    first_choice = choice(doors)
    print('User chooses door {}'.format(first_choice))
    doors.remove(winning_door)
    if first_choice == winning_door:
        opened_door = choice(doors)
        if switches:
            doors.remove(opened_door)
            second_choice = doors[0]
    else:
        doors.remove(first_choice)
        opened_door = doors[0]
        if switches:
            second_choice = winning_door
    print('Host opens door {}'.format(opened_door))
    if switches:
        print('User now chooses door {}'.format(second_choice))
    if ((switches and second_choice == winning_door) or
       (not switches and first_choice == winning_door)):
        print('Player wins!')
        count_of_wins += 1
    else:
        print('Player loses!')
    print('Player won {:.2f}% of times'.format(count_of_wins / nb_of_runs * 100))
              
          
            
        
        

Resource created Thursday 06 August 2015, 12:02:57 AM, last modified Thursday 06 August 2015, 12:03:11 AM.

file: monthy_hall.py


Back to top

COMP9021 15s2 (Principles of Programming) is powered by WebCMS3
CRICOS Provider No. 00098G