|
import random |
|
import streamlit as st |
|
import altair as alt |
|
import pandas as pd |
|
import time |
|
|
|
st.title("Monty Hall Problem Simulator") |
|
|
|
def simulate(iterations, no_of_doors): |
|
if no_of_doors < 3: |
|
st.warning("Number of doors must be at least 3", icon="π") |
|
return |
|
switch_win = 0 |
|
remain_win = 0 |
|
data = [] |
|
|
|
st.write(f"Simulation will loop for {iterations} iterations, with {no_of_doors} doors.") |
|
progress_bar = st.progress(0) |
|
chart_placeholder = st.empty() |
|
|
|
for _iter in range(iterations): |
|
doors = [0] * no_of_doors |
|
car_door = random.randint(0, len(doors) - 1) |
|
doors[car_door] = 1 |
|
choice_door = random.randint(0, len(doors) - 1) |
|
|
|
open_door = random.choice([i for i in range(len(doors)) if doors[i] == 0 and i != choice_door]) |
|
|
|
if doors[choice_door] == 1: |
|
remain_win += 1 |
|
else: |
|
switch_win += 1 |
|
|
|
data.append({ |
|
'Iteration': _iter + 1, |
|
'Switch Wins %': (switch_win / (_iter + 1)) * 100, |
|
'Remain Wins %': (remain_win / (_iter + 1)) * 100 |
|
}) |
|
|
|
progress_bar.progress((_iter + 1) / iterations) |
|
results_df = pd.DataFrame(data) |
|
line_chart = alt.Chart(results_df).mark_line().encode( |
|
x='Iteration:Q', |
|
y='value:Q', |
|
color='variable:N', |
|
tooltip=['Iteration:Q', 'value:Q', 'variable:N'] |
|
).transform_fold( |
|
['Switch Wins %', 'Remain Wins %'], |
|
as_=['variable', 'value'] |
|
).properties( |
|
title='Winning Outcomes Over Iterations' |
|
) |
|
|
|
chart_placeholder.altair_chart(line_chart, use_container_width=True) |
|
|
|
time.sleep(0.1) |
|
|
|
return pd.DataFrame(data) |
|
|
|
with st.form("Input"): |
|
no_of_doors = st.number_input("Enter number of doors", value=3) |
|
iterations = st.number_input("Enter number of iterations", value=100) |
|
state = st.form_submit_button("Start", type="primary") |
|
|
|
if state: |
|
if no_of_doors < 3: |
|
st.warning("No of doors must be at least 3", icon="π") |
|
else: |
|
results_df = simulate(iterations, no_of_doors) |
|
st.write(f"Winning scenarios for switching doors: {round(results_df['Switch Wins %'].iloc[-1]*iterations/100)}") |
|
st.write(f"Winning scenarios for sticking to the same door: {round(results_df['Remain Wins %'].iloc[-1]*iterations/100)}") |
|
st.write(f"Winning percentage for switching doors: {results_df['Switch Wins %'].iloc[-1]}%") |
|
st.write(f"Winning percentage for sticking to the same door: {results_df['Remain Wins %'].iloc[-1]}%") |