Skip to content

Instantly share code, notes, and snippets.

@Bachmann1234
Last active October 5, 2017 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Bachmann1234/62a51d27962ecbce121b58e164b3fff2 to your computer and use it in GitHub Desktop.
Save Bachmann1234/62a51d27962ecbce121b58e164b3fff2 to your computer and use it in GitHub Desktop.
Monty Hall Simulator
#!/usr/bin/env python3
import random
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
NUM_ROUNDS = 100000
def _get_doors():
doors = [False, False, False]
doors[random.randrange(0, len(doors))] = True
return doors
def _switch_door(doors, player_choice, door_with_goat):
potential_doors = set(range(0, len(doors)))
potential_doors.remove(player_choice)
potential_doors.remove(door_with_goat)
return random.choice(tuple(potential_doors))
def _reveal_goat(doors, player_choice):
potential_doors = set(range(0, len(doors)))
potential_doors.remove(player_choice)
while True:
potential_reveal = random.choice(tuple(potential_doors))
if not doors[potential_reveal]:
return potential_reveal
else:
potential_doors.remove(potential_reveal)
def play_monty_hall(switch):
'''
return true if game won
'''
doors = _get_doors()
logger.debug('There are {} doors'.format(len(doors)))
player_choice = random.randrange(0, len(doors))
logger.debug('Player has chosen door #{}'.format(player_choice + 1))
door_with_goat = _reveal_goat(doors, player_choice)
logger.debug('Monty has revealed door #{} to have a goat'.format(door_with_goat + 1))
if switch:
player_choice = _switch_door(doors, player_choice, door_with_goat)
logger.debug('Player has switched to door #{}'.format(player_choice +1))
else:
logger.debug('Player has chosen to stick with door #{}'.format(player_choice +1))
result = doors[player_choice]
if result:
logger.debug('Player has won the car! :-D')
else:
logger.debug('Player got a goat :-(')
return result
def play_iterated_monty_hall(switch, num_rounds):
'''
returns how many rounds you won playing X rounds
'''
return len(list(filter(lambda x: x, [play_monty_hall(switch) for _ in range(NUM_ROUNDS)])))
def main():
with_switching = play_iterated_monty_hall(True, NUM_ROUNDS)
with_sticking = play_iterated_monty_hall(False, NUM_ROUNDS)
print('With switching you won {}% of games'.format((with_switching/NUM_ROUNDS)*100))
print('With sticking you won {}% of games'.format((with_sticking/NUM_ROUNDS)*100))
if __name__ == '__main__':
main()
@Bachmann1234
Copy link
Author

Result
With switching you won 66.764% of games
With sticking you won 33.324% of games

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment