Python code n doors k revealed
Here another way in python to compare simulations with the general result in
Monty hall problem extended.
If extended to $n$ doors, $k$ doors are revealed by the host after the first choice, the probability of winning with switching and without switching changes slightly.
Here is the general formula for the Monty Hall problem with $n$ doors and $k$ revealed doors:
- If the player does not switch :
$$P(win) = 1/n$$
- If the player switches and the number of revealed doors is $k=n-2$ :
$$P(win) =\frac{n-1}{n}$$
- And in general for any number k of revealed doors:
$$0\leq k\leq n-2$$
$$P(win)=\frac{n-1}{n}\cdot \frac{1}{n-k-1} = \frac{1}{n} \cdot \frac{n-1}{n-k-1} \geq \frac{1}{n}$$
n=15
k=13# To simulate the original case k should be k=n-2 where p(win)=(n-1)/n
p_win_sw=((n-1)/n)*(1/(n-k-1))
p_win_no_sw=1/n
print('Total number of doors: ',n,'Number of revealed doors: ',k)
print("**********************************************************")
print('Probability of winning with switching: ',p_win_sw," = ", Fraction.from_float(p_win_sw).limit_denominator())
print('Probability of winning with NO switching:',p_win_no_sw," = ", Fraction.from_float(p_win_no_sw).limit_denominator())
import random
from fractions import Fraction
def simulate_game(switch, num_doors, k_revealed):
# Define the doors as a list of goats and a car
doors = ['goat'] * (num_doors - 1) + ['car']
# Shuffle the doors randomly
random.shuffle(doors)
# User chooses a door
first_choice = random.randint(0, num_doors - 1)
# Host reveals k_revealed doors with goats
revealed_doors = []
for i in range(num_doors):
if i != first_choice and doors[i] == 'goat' and len(revealed_doors) < k_revealed:
revealed_doors.append(i)
# User decides whether to switch or keep their original choice
if switch:
# If switching, the user must choose a door that was not already revealed
remaining_doors = [i for i in range(num_doors) if i not in revealed_doors and i != first_choice]
second_choice = random.choice(remaining_doors)
return doors[second_choice] == 'car'
else:
# If not switching, the user keeps their original choice
return doors[first_choice] == 'car'
# Simulate the game for a specified number of times
num_simulations = 100000
num_doors = n
k_revealed = k
num_wins_with_switching = 0
num_wins_without_switching = 0
for i in range(num_simulations):
if simulate_game(True, num_doors, k_revealed):
num_wins_with_switching += 1
if simulate_game(False, num_doors, k_revealed):
num_wins_without_switching += 1
# Print the results
print("**********************************************************")
print("Simulated probability of winning with switching: ", num_wins_with_switching / num_simulations)
print("Simulated probability of winning without switching: ", num_wins_without_switching / num_simulations)