Skip to content

Instantly share code, notes, and snippets.

@audhiaprilliant
Created April 25, 2022 15:29
Show Gist options
  • Select an option

  • Save audhiaprilliant/dbe7704042b0b8d28ec41977602c981b to your computer and use it in GitHub Desktop.

Select an option

Save audhiaprilliant/dbe7704042b0b8d28ec41977602c981b to your computer and use it in GitHub Desktop.
Simulation of Monty Hall Problem
# Monty Hall Problem
def monty_hall(
num_iter: int,
switch: bool
):
# Data object
obj = []
for iteration in range(num_iter):
# Possibilities in doors
doors = ['Car', 'Zonk', 'Zonk']
# Random doors
random.shuffle(doors)
# Index of doors
l_doors = list(range(0, 3))
# Dictionary of doors
d_doors = dict(zip(l_doors, doors))
# Participant select the initial door
index_initial = random.choice(l_doors)
# Host select the zonk door
d_zonks = {k:v for k, v in d_doors.items() if (k != index_initial and v == 'Zonk')}
index_zonk = random.choice(list(d_zonks.keys()))
# Strategy
if switch:
d_switch = {k:v for k, v in d_doors.items() if k not in [index_initial, index_zonk]}
switch_index, final_choice = list(d_switch.items())[0]
# Win-lose statistics
if final_choice == 'Car':
win, lose = 1, 0
else:
win, lose = 0, 1
else:
# Win-lose statistics
if d_doors[index_initial] == 'Car':
win, lose = 1, 0
else:
win, lose = 0, 1
# Assign new values into list
try:
l_temp = [d for d in obj if d['iter'] == iteration][0]
obj.append(
{
'iter': iteration + 1,
'win': l_temp['win'] + win,
'lose': l_temp['lose'] + lose
}
)
except:
obj.append(
{
'iter': iteration + 1,
'win': win,
'lose': lose
}
)
# Return list of object
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment