import random N = 3 TOTAL_GAMES = 10000 def monty_hall(should_switch): car = random.randrange(N) guess = random.randrange(N) # The host can only show you what's behind a door if there's a # goat behind the door AND that door isn't the one you chose shown = random.choice([i for i in range(N) if i != car and i != guess]) # Here, should_switch means we choose one of the doors that isn't if should_switch: guess = random.choice([i for i in range(N) if i != guess and i != shown]) return guess == car def multiple_choice(should_switch): '''Simulate a multiple choice question instead of Monty Hall. The main difference here is that this time the host can tell us that the answer we've picked is incorrect. If so, we choose randomly between the other questions. ''' car = random.randrange(N) guess = random.randrange(N) shown = random.choice([i for i in range(N) if i != car]) if shown == guess: guess = random.choice([i for i in range(N) if i != shown]) elif should_switch: guess = random.choice([i for i in range(N) if i != guess and i != shown]) return guess == car def chance_of_winning(game, should_switch): wins = 0 for i in range(TOTAL_GAMES): if game(should_switch): wins += 1 return wins * 1.0 / TOTAL_GAMES print('Running {} trials.'.format(TOTAL_GAMES)) print('Monty Hall:') print('Switching wins {}% of the time'.format( chance_of_winning(monty_hall, should_switch=True)) ) print('Not switching wins {}% of the time'.format( chance_of_winning(monty_hall, should_switch=False)) ) print('Mutliple Choice tests:') print('Switching wins {}% of the time'.format( chance_of_winning(multiple_choice, should_switch=True)) ) print('Not switching wins {}% of the time'.format( chance_of_winning(multiple_choice, should_switch=False)) )
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question